Springboot中使用springsecurity

Posted falcon_fei

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot中使用springsecurity相关的知识,希望对你有一定的参考价值。

简单记录springboot中使用springsecurity作为权限安全验证框架的步骤。

原理解析,连接分享。感觉写的不错记录下来

https://blog.csdn.net/code__code/article/details/53885510

 

添加引用

首先需要引入jar包,Maven坐标如下:

 

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

 

 

添加安全配置

使用注解的方式完成配置,同原XML配置。配置内容包括哪些页面需要进行验证,需要什么权限、角色等,详细配置见springsecurity相关配置文档,此处只记录简单配置。登录页、登陆接口等见以下代码种注释。

@Configuration

public class SecurityConfig  extends WebSecurityConfigurerAdapter {

    @Override

    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/dbinfo/man","/token/settings").authenticated().  //定义哪些页面需要登陆才能访问

                and().

                formLogin()

                .loginPage("/login")                    //设置登陆页面

                .loginProcessingUrl("/user/login")      //自定义的登陆接口

                .permitAll();





    }

}

 

实践种碰到的问题:

用了springsecurity后,post请求会被拦截,提示跨域问题。可以关闭默认开启的csrf拦截。 在配置类的config方法中加入:http.csrf().disable(); 

代码如下

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.authorizeRequests().antMatchers("/dbinfo/man","/token/settings").authenticated().  //定义哪些页面需要登陆才能访问
//                and().
//                formLogin()
//                .loginPage("/login")                    //设置登陆页面
//                .loginProcessingUrl("/user/login")      //自定义的登陆接口
//                .permitAll();

        http
            .authorizeRequests()
                .antMatchers("/dbinfo/man","/token/settings","/mailconfig").authenticated()
                .anyRequest().permitAll()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .logoutSuccessUrl("/")
                .permitAll();
        http.csrf().disable();          //POST跨域问题
    }

 















以上是关于Springboot中使用springsecurity的主要内容,如果未能解决你的问题,请参考以下文章

Activiti 7 springboot 工作流引擎

验证 Auth0 令牌 - Spring Security

手敲一个前后端分离项目——成果演示

反应式弹簧云安全(使用 Keycloak):会话到期?

使用 REST API 的 Spring Security 身份验证?

Spring Security:所有端点返回状态 200 并且对约束没有响应作为 antMatchers