spring-boot集成WebSecurity

你猜 阅读:401 2021-05-27 13:45:40 评论:0

一、注入依赖

<!-- 引入security模块 --> 
        <dependency> 
            <groupId>org.springframework.boot</groupId> 
            <artifactId>spring-boot-starter-security</artifactId> 
        </dependency>

二、编写配置类

import org.springframework.context.annotation.Configuration; 
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.builders.WebSecurity; 
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 
 
@Configuration 
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{ 
    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
        http 
                .authorizeRequests() 
                .antMatchers("/","/login").permitAll()//根路径和/login路径不拦截 
                .anyRequest().authenticated() 
                .and() 
                .formLogin() 
                .loginPage("/login") //2登陆页面路径为/login 
                .defaultSuccessUrl("/chat") //3登陆成功转向chat页面 
                .permitAll() 
                .and() 
                .logout() 
                .permitAll(); 
    } 
 
    //4在内存中配置两个用户 wyf 和 wisely ,密码和用户名一致,角色是 USER 
    @Override 
    protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
    		auth 
                .inMemoryAuthentication() 
                .withUser("admin").password("admin").roles("USER") 
                .and() 
                .withUser("abel").password("abel").roles("USER"); 
    } 
    //5忽略静态资源的拦截 
    @Override 
    public void configure(WebSecurity web) throws Exception { 
        web.ignoring().antMatchers("/resources/static/**"); 
    } 
 
}



标签:java
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

搜索
排行榜
关注我们

一个IT知识分享的公众号