推荐博客园地址
https://www.cnblogs.com/toov5/p/10324913.html
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.stereotype.Component;
import com.mayikt.handler.MyAuthenticationFailureHandler;
import com.mayikt.handler.MyAuthenticationSuccessHandler;
// Security 配置
@Component
@EnableWebSecurity //继承这个类
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyAuthenticationFailureHandler failureHandler;
@Autowired
private MyAuthenticationSuccessHandler successHandler;
// 配置认证用户信息和权限
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 添加admin账号
auth.inMemoryAuthentication().withUser("admin").password("123456").
authorities("showOrder","addOrder","updateOrder","deleteOrder");
// 添加userAdd账号
auth.inMemoryAuthentication().withUser("userAdd").password("123456").authorities("showOrder","addOrder");
// 如果想实现动态账号与数据库关联 在该地方改为查询数据库
}
// 配置拦截请求资源
protected void configure(HttpSecurity http) throws Exception {
// 如何权限控制 给每一个请求路径 分配一个权限名称 让后账号只要关联该名称,就可以有访问权限
http.authorizeRequests()
// 配置查询订单权限
.antMatchers("/showOrder").hasAnyAuthority("showOrder")
.antMatchers("/addOrder").hasAnyAuthority("addOrder")
.antMatchers("/login").permitAll() //登录请求不可以拦截!
.antMatchers("/updateOrder").hasAnyAuthority("updateOrder")
.antMatchers("/deleteOrder").hasAnyAuthority("deleteOrder")
.antMatchers("/**").fullyAuthenticated().and().formLogin().loginPage("/login"). //配置登录页面!!
successHandler(successHandler).failureHandler(failureHandler) //成功和失败的配置
.and().csrf().disable(); //csrf跨站点攻击关闭 否则必须要传递token!!
}
//因为是测试项目所以就不需要加密解密
@Bean
public static NoOpPasswordEncoder passwordEncoder() {
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}
}
配置认证
//认证失败
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse res, AuthenticationException auth)
throws IOException, ServletException {
System.out.println("登陆失败!");
res.sendRedirect("http://baidu.com");
}
}
// 认证成功
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication arg2)
throws IOException, ServletException {
System.out.println("用户认证成功");
res.sendRedirect("/");
}
}