Spring Security 入门(3-11)Spring Security 的使用-自定义登录验证和回调地址
- 配置文件 security-ns.xml
-
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security"
- xsi:schemaLocation="http:
- http:
-
-
- <security:http pattern="/openapi/**" security="none" />
- <security:http pattern="/useraccounts/userprofile.json" security="none" />
- <security:http pattern="/useraccounts/register**" security="none" />
-
-
- <security:http auto-config="false" entry-point-ref="authenticationEntryPoint">
- <security:intercept-url pattern="/backManage/**" access="ROLE_BACK_USER" />
- <security:intercept-url pattern="/mall/**" access="ROLE_BACK_USER" />
- <security:intercept-url pattern="/thirdUser/**" access="ROLE_USER" />
- <security:intercept-url pattern="/useraccounts/**" access="ROLE_USER" />
- <security:intercept-url pattern="/cart/**.html" access="ROLE_USER" />
- <security:intercept-url pattern="/ticket/**" access="ROLE_USER,ROLE_BACK_USER" />
- <security:intercept-url pattern="/order/**" access="ROLE_USER" />
- <security:intercept-url pattern="/comment/**" access="ROLE_USER" />
- <security:intercept-url pattern="/personal/**" access="ROLE_USER" />
- <security:intercept-url pattern="/favorite/**" access="ROLE_USER" />
-
-
- <security:custom-filter ref="myLoginFilter" position="FORM_LOGIN_FILTER" />
-
- <security:logout logout-success-url="${local.service.url}"/>
- </security:http>
-
-
- <bean id="encoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder"/>
-
- <security:authentication-manager alias="authenticationManager">
-
- <security:authentication-provider user-service-ref="userLoginService">
- <security:password-encoder ref="encoder">
- </security:password-encoder>
- </security:authentication-provider>
- </security:authentication-manager>
-
- <bean id="myLoginFilter" class="com.sale114.www.sercurity.MyUsernamePasswordAuthenticationFilter">
- <property name="authenticationManager" ref="authenticationManager"/>
- <property name="authenticationFailureHandler" ref="failureHandler"/>
- <property name="authenticationSuccessHandler" ref="successHandler"/>
- </bean>
-
-
- <bean id="successHandler" class="com.sale114.www.sercurity.MySavedRequestAwareAuthenticationSuccessHandler">
- <property name="defaultTargetUrl" value="${local.service.url}"/>
- </bean>
-
- <bean id="failureHandler" class="com.sale114.www.sercurity.MySimpleUrlAuthenticationFailureHandler">
- <property name="defaultFailureUrl" value="${local.service.url}/login.html?validated=false"/>
- </bean>
-
- <bean id="authenticationEntryPoint"
- class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
- <property name="loginFormUrl" value="${local.service.url}/login.html" />
- </bean>
- </beans>
-
-
- 2 UserLoginServiceImpl 查询用户实现类
-
- @Named("userLoginService")
- public class UserLoginServiceImpl implements UserDetailsService ,LoginService{
-
- @Inject
- private UserLoginDAO userLoginDAO;
-
- @Override
- public WrappedUserLogin getUserLogin() {
- try {
- WrappedUserLogin wrappedUserLogin = (WrappedUserLogin) SecurityContextHolder
- .getContext().getAuthentication().getPrincipal();
- return wrappedUserLogin;
- } catch (Exception e) {
- return null;
- }
- }
-
- @Override
- public UserDetails loadUserByUsername(String username)
- throws UsernameNotFoundException {
- System.out.println("用户名-------------"+username);
- UserLogin userLogin = null;
- if(username != null && !"".equals(username)&& username.indexOf("@") > 0){
- userLogin = userLoginDAO.findByEmail(username);
- username = userLogin.getNick();
- }else{
- userLogin = userLoginDAO.findByNick(username);
- }
- System.out.println("user is null ---"+userLogin.getUserType());
- String nick = userLogin.getNick();
- String email = userLogin.getEmail();
- String mobile = userLogin.getMobile();
- int userType = userLogin.getUserType();
- List<GrantedAuthority> resultAuths = new ArrayList<GrantedAuthority>();
-
-
-
- if (userType == 1) {
- resultAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
- } else {
- resultAuths.add(new SimpleGrantedAuthority("ROLE_BACK_USER"));
- }
-
- return new WrappedUserLogin(userLogin.getId(), email, nick, mobile, userLogin.getPassword(), userType,resultAuths);
- }
-
- }
-
- 3 重写用户名密码验证
- public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
-
- public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "j_username";
-
- public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "j_password";
-
- public static final String SPRING_SECURITY_FORM_REDERICT_KEY = "spring-security-redirect";
-
- /**
- * @deprecated If you want to retain the username, cache it in a customized {@code AuthenticationFailureHandler}
- */
- @Deprecated
- public static final String SPRING_SECURITY_LAST_USERNAME_KEY = "SPRING_SECURITY_LAST_USERNAME";
-
- private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY;
- private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;
- private String redirectParameter = SPRING_SECURITY_FORM_REDERICT_KEY;
- private boolean postOnly = true;
-
-
-
- public MyUsernamePasswordAuthenticationFilter() {
- super();
- }
-
-
-
- public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
- if (postOnly && !request.getMethod().equals("POST")) {
- throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
- }
- String username = obtainUsername(request);
- String password = obtainPassword(request);
- String redirectUrl = obtainRedercitUrl(request);
- if (username == null) {
- username = "";
- }
-
- if (password == null) {
- password = "";
- }
-
- if(redirectUrl != null && !"".equals(redirectUrl)){
- request.getSession().setAttribute("callCustomRediretUrl", redirectUrl);
- }
- username = username.trim();
- UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
-
- setDetails(request, authRequest);
- return this.getAuthenticationManager().authenticate(authRequest);
- }
-
-
- protected String obtainPassword(HttpServletRequest request) {
- return request.getParameter(passwordParameter);
- }
-
-
- protected String obtainUsername(HttpServletRequest request) {
- return request.getParameter(usernameParameter);
- }
-
-
- protected String obtainRedercitUrl(HttpServletRequest request) {
- return request.getParameter(redirectParameter);
- }
-
-
- protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {
- authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
- }
-
-
- public void setUsernameParameter(String usernameParameter) {
- Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
- this.usernameParameter = usernameParameter;
- }
-
-
- public void setPasswordParameter(String passwordParameter) {
- Assert.hasText(passwordParameter, "Password parameter must not be empty or null");
- this.passwordParameter = passwordParameter;
- }
-
-
- public void setPostOnly(boolean postOnly) {
- this.postOnly = postOnly;
- }
-
-
- }
-
-
-
- 4 SimpleUrlAuthenticationSuccessHandler重写
- public class MySavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler{
- @Value(value = "${local.service.url}")
- private String LOCAL_SERVER_URL;
-
- protected final Log logger = LogFactory.getLog(this.getClass());
-
- private RequestCache requestCache = new HttpSessionRequestCache();
-
- @Override
- public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
- Authentication authentication) throws ServletException, IOException {
- SavedRequest savedRequest = requestCache.getRequest(request, response);
- if (savedRequest == null) {
- System.out.println("savedRequest is null ");
-
- int flag = 0;
-
- if(request.getSession().getAttribute("callCustomRediretUrl") != null && !"".equals(request.getSession().getAttribute("callCustomRediretUrl"))){
- String url = String.valueOf(request.getSession().getAttribute("callCustomRediretUrl"));
-
- super.setDefaultTargetUrl(url);
- super.setAlwaysUseDefaultTargetUrl(true);
- flag = 1;
- request.getSession().setAttribute("callCustomRediretUrl", "");
- }
-
- if(flag == 0){
- super.setDefaultTargetUrl(LOCAL_SERVER_URL);
- }
- super.onAuthenticationSuccess(request, response, authentication);
-
- return;
- }
-
- String targetUrlParameter = getTargetUrlParameter();
- if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
- requestCache.removeRequest(request, response);
- super.setAlwaysUseDefaultTargetUrl(false);
- super.setDefaultTargetUrl("/");
- super.onAuthenticationSuccess(request, response, authentication);
- return;
- }
-
- clearAuthenticationAttributes(request);
-
- String targetUrl = savedRequest.getRedirectUrl();
- logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
- if(targetUrl != null && "".equals(targetUrl)){
- targetUrl = LOCAL_SERVER_URL;
- }
- getRedirectStrategy().sendRedirect(request, response, targetUrl);
- }
-
- public void setRequestCache(RequestCache requestCache) {
- this.requestCache = requestCache;
- }
- }
-
- 5 认证失败控制类重写
- public class MySimpleUrlAuthenticationFailureHandler implements AuthenticationFailureHandler{
-
- protected final Log logger = LogFactory.getLog(getClass());
-
- private String defaultFailureUrl;
- private boolean forwardToDestination = false;
- private boolean allowSessionCreation = true;
- private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
- @Value(value = "${local.service.url}")
- private String LOCAL_SERVER_URL;
-
- public MySimpleUrlAuthenticationFailureHandler() {
- }
-
- public MySimpleUrlAuthenticationFailureHandler(String defaultFailureUrl) {
- setDefaultFailureUrl(defaultFailureUrl);
- }
-
-
- public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
- AuthenticationException exception) throws IOException, ServletException {
-
- if(request.getParameter("spring-security-redirect") != null){
- request.getSession().setAttribute("callUrlFailure", request.getParameter("spring-security-redirect"));
- }
-
- if(request.getParameter("loginUrl") != null && !"".equals(request.getParameter("loginUrl"))){
- defaultFailureUrl = LOCAL_SERVER_URL+"/backlogin.html?validated=false";
- }
-
- if (defaultFailureUrl == null) {
- logger.debug("No failure URL set, sending 401 Unauthorized error");
- response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed: " + exception.getMessage());
- } else {
- saveException(request, exception);
- if (forwardToDestination) {
- logger.debug("Forwarding to " + defaultFailureUrl);
- request.getRequestDispatcher(defaultFailureUrl).forward(request, response);
- } else {
- logger.debug("Redirecting to " + defaultFailureUrl);
- redirectStrategy.sendRedirect(request, response, defaultFailureUrl);
- }
- }
- }
-
-
- protected final void saveException(HttpServletRequest request, AuthenticationException exception) {
- if (forwardToDestination) {
- request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
- } else {
- HttpSession session = request.getSession(false);
-
- if (session != null || allowSessionCreation) {
- request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
- }
- }
- }
-
-
- public void setDefaultFailureUrl(String defaultFailureUrl) {
- this.defaultFailureUrl = defaultFailureUrl;
- }
-
- protected boolean isUseForward() {
- return forwardToDestination;
- }
-
-
- public void setUseForward(boolean forwardToDestination) {
- this.forwardToDestination = forwardToDestination;
- }
-
-
- public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
- this.redirectStrategy = redirectStrategy;
- }
-
- protected RedirectStrategy getRedirectStrategy() {
- return redirectStrategy;
- }
-
- protected boolean isAllowSessionCreation() {
- return allowSessionCreation;
- }
-
- public void setAllowSessionCreation(boolean allowSessionCreation) {
- this.allowSessionCreation = allowSessionCreation;
- }
-
- }
原文地址:https://www.cnblogs.com/lexiaofei/p/7018818.html