Spring Security与Spring Boot集成

在之前的项目的基础上进行修改的
添加依赖
build.gradle

// 添加  Spring Security 依赖
    compile('org.springframework.boot:spring-boot-starter-security')
// 添加   Thymeleaf Spring Security 依赖
    compile('org.thymeleaf.extras:thymeleaf-extras-springsecurity4:3.0.2.RELEASE')

cmd命令下gradlew bootRun运行

新建SecurityConfig继承WebSecurityConfigurerAdapter

@EnableWebSecurity  //启用security安全
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    /*自定义配置
     * (non-Javadoc)
     * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/css/**","/js/**","/fonts/**","/index").permitAll()//在拦截的状态  只有这些才可以访问
            .antMatchers("/users/**").hasRole("ADMIN") //需要相应的角色才能访问
            .and()
            .formLogin()  //基于Form 表单登录验证
            .loginPage("/login").failureUrl("/login-error"); //自定义登录界面  失败后就重定向到/login-error
        //不登录访问其他页面的时候  被拦截  跳到 login.html
        //当访问登录表单提交到login的时候  被拦截下来  去执行configureGlobal判断是否是认证信息
    }

    /*
     * 认证信息管理
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
        auth.inMemoryAuthentication()//认证信息存储与内存中   也可以存储在数据库当中
            .withUser("binglo").password("123456").roles("ADMIN"); //在内存中初始化的认证信息  

    }
}

写个控制器MainController

/*
 * 主页控制器
 */
@Controller
public class MainController {

    @GetMapping("/")
    public String root(){
        return "redirect:/index";
    }

    @GetMapping("/index")
    public String index(){
        return "index";
    }

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @GetMapping("/login-error")
    public String loginError(Model model){
        model.addAttribute("loginError",true);
        model.addAttribute("errormsg", "登陆失败,用户名或者密码错误");
        return "login";
    }
}

前端index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
    xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
    xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"> <!-- 这个记得写 -->
<head th:replace="~{fragments/header :: header}">
</head>
<body>
    <div class="container blog-content-container">
        <div sec:authorize="isAuthenticated()"><!-- 如果认证就会显示这个div -->
            <p>已有用户登录</p>
            <p>登录的用户为:<span sec:authentication="name"></span></p>
            <p>用户的角色为:<span sec:authentication="principal.authorities"></span></p>
        </div>
        <div sec:authorize="isAnonymous()"><!-- 未认证就显示这个div -->
            <p>未有用户登录</p>
        </div>
        <!-- /.row -->
    </div>
    <!-- /.container -->
    <div th:replace="~{fragments/footer :: footer}">...</div>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/guo_binglo/article/details/80470419