使用Spring Security和jdbc的Spring Boot

Spring安全性是一个很棒的框架,可节省开发人员的大量时间和精力。 此外,它还具有足够的灵活性,可以自定义并满足您的需求。

使用JDBC和Spring Security非常容易,并且许多操作是自动化的。 这将是一个最小的展示。

gradle文件包含诸如spring-security,spring-jdbc和h2数据库之类的依赖项

group 'com.gkatzioura'
version '1.0-SNAPSHOT'

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.0.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'spring-boot'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.thymeleaf:thymeleaf-spring4")
    compile("org.springframework.boot:spring-boot-starter-security")
    compile("org.springframework:spring-jdbc")
    compile("com.h2database:h2:1.4.192")
    compile("org.slf4j:slf4j-api:1.6.6")
    compile("ch.qos.logback:logback-core:1.1.7")
    compile("ch.qos.logback:logback-classic:1.1.7")
    testCompile "junit:junit:4.11"
}

必须创建包含某些信息的表。 这些表将具有Spring安全性查询的默认名称和列名称,以获取信息。

drop table if exists users;
create table users(id bigint auto_increment, username varchar(255), password varchar(255), enabled boolean);
insert into users(username,password,enabled) values('steve','steve',true);
insert into users(username,password,enabled) values('john','john',true);
drop table if exists authorities;
create table authorities(username  varchar(255),authority  varchar(255), UNIQUE(username,authority));
insert into authorities(username,authority) values('steve','admin');
insert into authorities(username,authority) values('john','superadmin');

这些sql语句将驻留在resources / schema.sql上。

第一步是创建我们的Application类

package com.gkatzioura.spring.security;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Created by gkatzioura on 9/2/16.
 */
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

为了快速入门,该数据库将为h2数据库。

package com.gkatzioura.spring.security.config;

import org.h2.jdbcx.JdbcDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.nio.file.Files;

/**
 * Created by gkatzioura on 9/2/16.
 */
@Configuration
public class DataSourceConfig {

    @Bean
    public DataSource createDataSource() {

        JdbcDataSource dataSource = new JdbcDataSource();
        dataSource.setURL("jdbc:h2:"+System.getProperty("java.io.tmpdir")+"/database");

        return dataSource;
    }

}

通过指定h2数据库,我将该目录设置为临时目录内。 因此,一旦重新启动操作系统,数据库将消失。
如前所述以前一旦数据源豆已初始化弹簧JDBC会自动查找上一个schema.sql文件的文件资源文件夹。 如果文件存在,spring-jdbc将尝试执行schema.sql包含的语句。

下一步是定义我们的安全配置。 我们必须指定我们的安全性将基于jdbc。 同样,我们必须定义必须安全的端点。

package com.gkatzioura.spring.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import javax.sql.DataSource;

/**
 * Created by gkatzioura on 9/2/16.
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers("/public").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }
}

最后但并非最不重要的一点是,我们将添加具有安全端点和非安全端点的控制器

package com.gkatzioura.spring.security.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by gkatzioura on 9/2/16.
 */
@RestController
public class GreetController {

    private static final Logger LOGGER = LoggerFactory.getLogger(GreetController.class);

    @RequestMapping(path = "/public",method = RequestMethod.GET)
    public String sayFreeHi() {
        return "Greeting";
    }

    @RequestMapping(path = "/secured",method = RequestMethod.GET)
    public String saySecureHi() {
        return "Secured";
    }

}

一旦尝试访问安全端点,将显示默认的spring security登录屏幕。
继续执行sql语句中指定的用户之一(例如,用户名:steve密码:steve)。 如果您要注销,只需点击/ login?logout端点即可。

运行带有

gradle bootRun

而且你很好。

您可以在github上找到源代码

翻译自: https://www.javacodegeeks.com/2016/09/spring-boot-spring-security-jdbc.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值