package com.example.myblog.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class securityConfig extends WebSecurityConfigurerAdapter {
//这边是配置一个不加密,这是一个过期的方法
@Bean
PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();
}
/*
* 这个是配置spring security自身的登录验证
* */
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
//配置spring security的登录用户,这边是两个用户
//spring5之后的密码需要加密,不然是会有问题的。
.withUser("lionboy")
.password("123")
.roles("admin")
.and()
.withUser("lionboy2")
.password("123")
.roles("user");
}
/*
* 这个是配置项目的路径拦截的登录认证
* */
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("admin")
.antMatchers("/user/**").hasAnyRole("admin","user")
.antMatchers("/stu/**").access("hasAnyRole('user','admin')")
.anyRequest().authenticated()
.and()
.formLogin()
.loginProcessingUrl("/doLogin")
.loginPage("/login")//这里是默认的登陆页面,可以配置自己的页面
.usernameParameter("uname")
.passwordParameter("passwd")
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication auth) 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",auth.getPrincipal());//登录成功的用户对象
out.write(new ObjectMapper().writeValueAsString(map));
out.flush();
out.close();
}
})//前后端分离使用,登录成功后跳转
//前后端不分离使用 //.successForwardUrl()
.failureHandler(new AuthenticationFailureHandler() {
@Override
public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
/*
* AuthenticationException e
* 这边是异常,更具异常判断失败的原因
* */
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));
out.flush();
out.close();
}
})
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessHandler(new LogoutSuccessHandler() {
@Override
public void onLogoutSuccess(HttpServletRequest rep, HttpServletResponse resp, Authentication auth) 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));
out.flush();
out.close();
}
})
.and()
.csrf().disable();//关闭csrf攻击
}
}
springsecurity的配置,登录注销
最新推荐文章于 2023-04-15 08:00:00 发布