package com.msb.springsecuritydemo.config;
import com.msb.springsecuritydemo.exception.MyAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
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.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.applet.AudioClip;
import java.io.IOException;
/**
* 自定义登录页面
*/
@Configuration
public class MyWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Autowired
private MyAccessDeniedHandler myAccessDeniedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception{
http.formLogin() //和表单有关系
.loginPage("/showLogin")
.loginProcessingUrl("/login")
.successForwardUrl("/showMain")
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.sendRedirect("/showMain");
}
})
//认证失败转发的url地址
.failureForwardUrl("/showFail")
.failureHandler(new AuthenticationFailureHandler() {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
response.sendRedirect("/showFail"); //设置重定向
}
})
//客户端用户名参数名称
.usernameParameter("myUsername")
//客户端密码参数名称
.passwordParameter("myPassword")
;
// http.authorizeRequests() 授权相关
//配置登录页面的放行
http.authorizeRequests()
.antMatchers("/showLogin","/showFail").permitAll()
// .antMatchers("js/**").permitAll()
.antMatchers("/abc").denyAll()
.antMatchers("js/.*").permitAll()
.anyRequest().authenticated();
http.exceptionHandling()
.accessDeniedHandler(myAccessDeniedHandler)
//只适用非前端方式,适用同步请求方式,所有异步(ajax)使用accessDeniedHandler
.accessDeniedPage("/showAccessDenied");
http.csrf().disable();
}
}
自定义登录页面