依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
自定义类继承WebSecurityConfigurerAdapter,并重写了2个configure方法(分别是认证方法和授权方法)
不对密码进行加密,但是必须指定一个PasswordEncoder,不然报PasswordEncoder错!
@Bean
PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();
}
定义认证规则
定义了3个角色
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("root").password("123").roles("ADMIN","DBA")
.and()
.withUser("admin").password("123").roles("ADMIN","USER")
.and()
.withUser("zhou").password("123").roles("USER");
}
**
/**
* 定义授权规则
* http.authorizeRequests() 开启HttpSecurity的配置
* permitAll() 不需要认证就可访问
* anyRequest().authenticated(),除使用antMatchers已定义的URL外,其它全部需要认证
* formLogin()
* 没有使用loginPage自定义页面时(路径!!!), 默认使用security的login页面
*
* 默认使用登陆参数名:username,password
*.csrf().disable()不能省略,否则会重定向回login页面
注:自定义登录页面时中action的URL需要跟配置类中的loginPage的URL一致
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/index/**").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/root/**").access("hasRole('ADMIN') and hasRole('USER')")
.antMatchers("/dba/**").hasRole("DBA")
.antMatchers("/user/**").access("hasAnyRole('ADMIN','USER')")
.anyRequest().authenticated();
http.formLogin().usernameParameter("username")
.passwordParameter("password")
.loginProcessingUrl("/login")
/**
* 验证成功
* 登陆成功的用户信息
* auth.getPrincipal();
*/
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication auth) throws IOException, ServletException {
Object principal = auth.getPrincipal();
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
resp.setStatus(200);
Map<String,Object> map=new HashMap<>();
map.put("status",200);
map.put("msg",principal);
//jackJSon
ObjectMapper om=new ObjectMapper();
out.write(om.writeValueAsString(map));
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();
resp.setStatus(401);
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","登录失败!");
}
ObjectMapper om=new ObjectMapper();
out.write(om.writeValueAsString(map));
out.flush();
out.close();
}
})
.permitAll()
.and()
.logout().logoutSuccessUrl("/login_page")
.and().csrf().disable();
}