spring security

springboot +spring security 

1.maven依赖:

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

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

2.配置文件


@Configuration
public class SecuriltyConfig extends WebSecurityConfigurerAdapter {

@Bean
PasswordEncoder passwordEncoder(){
//不加密的密码
return NoOpPasswordEncoder.getInstance();
}


//自定义用户和密码,优先级大于配置文件中的
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password("123")
.roles("admin");
}

//开放静态文件
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/js/***","/css/**","images/**");
}

//自定义登录页面
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
//默认的登录action名是 /login.html
.loginPage("/login.html")
//配置登录接口名,不配就是上面的的那个
// .loginProcessingUrl("login")
//登录参数
.usernameParameter("username")
.passwordParameter("password")
//登录成功后的跳转,服务端跳转,url不变
// .successForwardUrl("/s")
//登录成功后的跳转,重定向到之前的请求
.defaultSuccessUrl("/hello")
.permitAll()
.and()
//配置退出页的路由和页面
.logout()
.logoutUrl("aaa")
.logoutSuccessUrl("/login.html")
.deleteCookies()
//clearAuthentication 和 invalidateHttpSession 分别表示清除认证信息和使 HttpSession 失效,默认可以不用配置,默认就会清除
.and()
.csrf().disable();

}
}
 
原文地址:https://www.cnblogs.com/qq1069284034/p/14453411.html