Spring Security权限管理
Posted feilinli
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Security权限管理相关的知识,希望对你有一定的参考价值。
Spring Security权限管理
- 2 HttpSecurity的配置
- 3 登录/注销表单详细配置
- 4 多个HttpSecurity的配置
- 5 密码加密
- 6 方法安全
- 7 基于数据库的认证
- 8 角色继承(在securityConfig中加入代码段)
- 9 动态配置权限
1 Spring Security配置用户名和密码
方式一:在application.properties文件中配置
# 配置security用户名密码
spring.security.user.password=LIFEILIN
spring.security.user.name=LIFEILIN
spring.security.user.roles=admin
方式二:代码配置
@Configuration
public class securityConfig extends WebSecurityConfigurerAdapter
//暂且密码不加密
@Bean
PasswordEncoder passwordEncoder()
return NoOpPasswordEncoder.getInstance();
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
auth.inMemoryAuthentication()
.withUser("LIFEILIN").password("LIFEILIN").roles("admin") //第一个
.and()
.withUser("123").password("123").roles("user"); //第二个
2 HttpSecurity的配置
//配置HttpSecurity拦截规则
@Override
protected void configure(HttpSecurity http) throws Exception
http.authorizeRequests() //开启配置
.antMatchers("/admin/**").hasRole("admin")
.antMatchers("/user/**").hasAnyRole("admin","user")
.anyRequest().authenticated() //其他请求登录后即可访问
.and()
.formLogin()
.loginProcessingUrl("/doLogin")
.permitAll() //跟登录相关接口直接访问
.and()
.csrf().disable();
3 登录/注销表单详细配置
//配置HttpSecurity拦截规则
@Override
protected void configure(HttpSecurity http) throws Exception
http.authorizeRequests() //开启配置
.antMatchers("/admin/**").hasRole("admin")
.antMatchers("/user/**").hasAnyRole("admin", "user")
.anyRequest().authenticated() //其他请求登录后即可访问
.and()
.formLogin()
.loginProcessingUrl("/doLogin")
// .loginPage("login") //登录页面
//自定义用户名密码
.usernameParameter("uname")
.passwordParameter("passwd")
//登录成功的处理器(前后端分离)
.successHandler(new AuthenticationSuccessHandler()
@Override
public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException //authentication为登录成功对象
//登录成功,返回json
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
Map<String, Object> map = new HashMap<>();
map.put("status", 200);
map.put("msg", authentication.getPrincipal()); //登录成功对象
out.write(new ObjectMapper().writeValueAsString(map)); //将map转为json写出去
out.flush();
out.close();
)
//登录失败的处理器(前后端分离)
.failureHandler(new AuthenticationFailureHandler()
@Override
public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
Map<String, Object> map = new HashMap<>();
map.put("status", 401);
if (e instanceof LockedException) //账号锁定
map.put("msg","账号被锁定,登录失败");
else if (e instanceof BadCredentialsException)
map.put("msg","用户名和密码输入错误,登录失败");
else if (e instanceof DisabledException)
map.put("msg","账号被禁用,登录失败");
else if (e instanceof AccountExpiredException)
map.put("msg","账户过期,登录失败");
else if (e instanceof CredentialsExpiredException)
map.put("msg","密码过期,登录失败");
else
map.put("msg","登录失败");
out.write(new ObjectMapper().writeValueAsString(map)); //将map转为json写出去
out.flush();
out.close();
)
.permitAll() //跟登录相关接口直接访问
.and()
//注销登录
.logout()
.logoutUrl("/logout")
.logoutSuccessHandler(new LogoutSuccessHandler()
@Override
public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
Map<String, Object> map = new HashMap<>();
map.put("status", 200);
map.put("msg", "注销登录成功"); //注销登录成功
out.write(new ObjectMapper().writeValueAsString(map)); //将map转为json写出去
out.flush();
out.close();
)
.and()
.csrf().disable();
4 多个HttpSecurity的配置
配置类不需要继承WebSecurityConfigurerAdapter方法,直接注入:configure方法
@Configuration
public class MultiHttpSecurityConfig
//暂且密码不加密
@Bean
PasswordEncoder passwordEncoder()
return NoOpPasswordEncoder.getInstance();
//配置用户名和密码
@Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception
auth.inMemoryAuthentication()
.withUser("LIFEILIN").password("LIFEILIN").roles("admin") //第一个
.and()
.withUser("123").password("123").roles("user"); //第二个
@Configuration
@Order(1)
public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter
@Override
protected void configure(HttpSecurity http) throws Exception
http.antMatcher("/admin/**").authorizeRequests().anyRequest().hasRole("admin"); //admin角色访问
@Configuration
public static class OtherSecurityConfig extends WebSecurityConfigurerAdapter
@Override
protected void configure(HttpSecurity http) throws Exception
http.authorizeRequests().anyRequest().authenticated()
.and()
.formLogin()
.loginProcessingUrl("/doLogin")
.permitAll()
.and()
.csrf().disable();
5 密码加密
相同的明文可加密成不同的密文,不用维护原字段。
@Test
void contextLoads()
for (int i=0;i<10;i++)
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
System.out.println(encoder.encode("123"));
明文【123】加密后:
$2aSS.YDon5lzqkIFdW8DQYzOTJBvQwkdXHWcHlIfF1fa/wPjJtru5aO
$2avJsPq4GBtHKmmBQaKTriTO90sFurCEDavZANqCoqGu4gAzXxGLbTC
$2agZ4H3/tBRpz2lPX0XUI1ber2qsNsKuk38j0iSsATeVOrrWFJIEr1G
$2ah7RiyAXP8JzWGsmAXGZy/uO6ASraQPNryVPl.11vMyUjhSCxS.Sde
$2aBCm3vuueGWdvjG3ciCUZB.6V9y6jMELHqB9iv2DwRJyOkR5jd…4S
$2arO2894WmxRMtjHVzoYivyuzvje8BrAUjm8YLj3K.i4sQDvpWBtuuy
$2ajTosyN75hwKB3OSQCYY9YOIj6TYZG1FdJXfYCalTUuXpPiI5tv/P.
$2ap95j18H3yRABEScCE/2MqOqYt1ZqArdYhC87BVGEmQvn6znSqKw5G
$2a/y8FGBlvod1Dnq29c2scs.eGnYfvezZIZwfDHoXFfgIVA7H0T17pO
$2aSpring Security 权限管理
安全框架Spring Security是什么?如何理解Spring Security的权限管理?