security个性化用户认证流程二

流程一说的是自定义页面处理,一会马上立刻现在就说,这里学的是自定义登录成功和失败的处理。这不,你看,开始了吧:

security个性化用户认证流程二_第1张图片

package com.imooc.security.browser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.imooc.security.browser.authentication.ImoocAuthenticationSuccessHandler;
import com.imooc.security.core.properties.SecurityProperties;

@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter{
   
	@Autowired
	private SecurityProperties securityProperties;
	
	//让系统使用我们自定义 而不是系统默认的配置
	@Autowired
	private ImoocAuthenticationSuccessHandler imoocAuthenticationSuccessHandler;
	
	@Bean
	public PasswordEncoder passwordEncoder() {
		//这里如果是自己编写的加密 则调用自己的类 方法有编码和解码验证方法
		return new BCryptPasswordEncoder();
	}
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		
		http.formLogin()//认证
		.loginPage("/authentication/require")//设置登录页面
		.loginProcessingUrl("/authentication/form")//遇到该请求则进行user password认证
		.successHandler(imoocAuthenticationSuccessHandler)//成功后 使用我们自己的处理器处理
//		http.httpBasic()
		.and()
		.authorizeRequests()//授权
		//当访问这个路径的时候不需要身份认证 除了它其他的是需要身份认证
		.antMatchers("/authentication/require"
				,securityProperties.getBrowsers().getLoginPage()).permitAll()
		.anyRequest()
		.authenticated()
		.and()
		.csrf().disable();
	}
    
}
/**
 * 
 */
package com.imooc.security.browser.authentication;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author 35-pxiaodong
 *
 */
@Component("imoocAuthenticationSuccessHandler")
public class ImoocAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
     
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private ObjectMapper objectMapper;//启动的时候springmvc会注册一个mapper
	
	/* (non-Javadoc)
	 * @see org.springframework.security.web.authentication.AuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.Authentication)
	 */
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		
		logger.info("登录成功");
		
		response.setContentType("application/json,charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(authentication));
        
	}

}

相对上一个版本,只有这俩类有变动,启动访问结果:

security个性化用户认证流程二_第2张图片

security个性化用户认证流程二_第3张图片访问成功时返回的authentication内容如右图。

人生不如意十有八九,也不都是充满着成功的喜悦,偶尔有失败的阴影,但是要学会处理失败的情况,就很伟大了,接下来做的就是伟大的事:

security个性化用户认证流程二_第4张图片

/**
 * 
 */
package com.imooc.security.browser.authentication;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author 35-pxiaodong
 *
 */
@Component("imoocAuthenticatinFailureHandler")
public class ImoocAuthenticatinFailureHandler implements AuthenticationFailureHandler {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private ObjectMapper objectMapper;//启动的时候springmvc会注册一个mapper
	
	/* (non-Javadoc)
	 * @see org.springframework.security.web.authentication.AuthenticationFailureHandler#onAuthenticationFailure(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException)
	 */
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
          
		logger.info("登录失败");
		
		response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());//设置错误500状态
		response.setContentType("application/json,charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(exception));
	}

}
package com.imooc.security.browser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.imooc.security.browser.authentication.ImoocAuthenticationSuccessHandler;
import com.imooc.security.core.properties.SecurityProperties;

@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter{
   
	@Autowired
	private SecurityProperties securityProperties;
	
	//让系统使用我们自定义 而不是系统默认的配置
	@Autowired
	private AuthenticationSuccessHandler imoocAuthenticationSuccessHandler;
	
    @Autowired
    private AuthenticationFailureHandler imoocAuthenticationFailureHandler;
	
	@Bean
	public PasswordEncoder passwordEncoder() {
		//这里如果是自己编写的加密 则调用自己的类 方法有编码和解码验证方法
		return new BCryptPasswordEncoder();
	}
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		
		http.formLogin()//认证
		.loginPage("/authentication/require")//设置登录页面
		.loginProcessingUrl("/authentication/form")//遇到该请求则进行user password认证
		.successHandler(imoocAuthenticationSuccessHandler)//成功后 使用我们自己的处理器处理
		.failureHandler(imoocAuthenticationFailureHandler)//设置失败处理器
//		http.httpBasic()
		.and()
		.authorizeRequests()//授权
		//当访问这个路径的时候不需要身份认证 除了它其他的是需要身份认证
		.antMatchers("/authentication/require"
				,securityProperties.getBrowsers().getLoginPage()).permitAll()
		.anyRequest()
		.authenticated()
		.and()
		.csrf().disable();
	}
    
}

启动测试结果:注意,这里要输入一个错误密码。

security个性化用户认证流程二_第5张图片

security个性化用户认证流程二_第6张图片

看到这里你可能会是蒙蔽的,怎么这么多json,看不过来啊,嘿嘿嘿,咻咻咻,接下来带你配置成跳转页面或json自定义:

security个性化用户认证流程二_第7张图片

/**
 * 
 */
package com.imooc.security.browser.authentication;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.security.core.properties.LoginType;
import com.imooc.security.core.properties.SecurityProperties;

/**
 * @author 35-pxiaodong
 *
 */
@Component("imoocAuthenticatinFailureHandler")
public class ImoocAuthenticatinFailureHandler 
     extends SimpleUrlAuthenticationFailureHandler {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private ObjectMapper objectMapper;//启动的时候springmvc会注册一个mapper
	
	@Autowired
	private SecurityProperties securityProperties;
	
	/* (non-Javadoc)
	 * @see org.springframework.security.web.authentication.AuthenticationFailureHandler#onAuthenticationFailure(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException)
	 */
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
          
		logger.info("登录失败");
		//返回json
		if (LoginType.JSON.equals(securityProperties.getBrowsers().getLoginType())) {
			response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());//设置错误500状态
			response.setContentType("application/json,charset=UTF-8");
	        response.getWriter().write(objectMapper.writeValueAsString(exception));
		}else {//返回页面
			super.onAuthenticationFailure(request, response, exception);;//父类的方法就是跳转
		}
	}

}
/**
 * 
 */
package com.imooc.security.browser.authentication;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.security.core.properties.LoginType;
import com.imooc.security.core.properties.SecurityProperties;

/**
 * @author 35-pxiaodong
 *
 */
@Component("imoocAuthenticationSuccessHandler")
public class ImoocAuthenticationSuccessHandler 
     extends SavedRequestAwareAuthenticationSuccessHandler {
     
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private ObjectMapper objectMapper;//启动的时候springmvc会注册一个mapper
	
	@Autowired
	private SecurityProperties securityProperties;
	
	/* (non-Javadoc)
	 * @see org.springframework.security.web.authentication.AuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.Authentication)
	 */
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		
		logger.info("登录成功");
		
		//返回json
		if (LoginType.JSON.equals(securityProperties.getBrowsers().getLoginType())) {
			response.setContentType("application/json,charset=UTF-8");
	        response.getWriter().write(objectMapper.writeValueAsString(authentication));
		}else {//返回页面
			super.onAuthenticationSuccess(request, response, authentication);//父类的方法就是跳转
		}
	}

}

security个性化用户认证流程二_第8张图片

package com.imooc.security.core.properties;

public class BrowserProperties {
	
	//设定默认值如果没有指定loginPage则访问该页面
	private String loginPage = "/imooc-signIn.html";

	private LoginType loginType=LoginType.JSON;//默认返回json
	
	public String getLoginPage() {
		return loginPage;
	}

	public void setLoginPage(String loginPage) {
		this.loginPage = loginPage;
	}

	public LoginType getLoginType() {
		return loginType;
	}

	public void setLoginType(LoginType loginType) {
		this.loginType = loginType;
	}
	
}
package com.imooc.security.core.properties;

public enum LoginType {
   
	REDIRECT,//返回页面
	
	JSON//返回json
	
}

security个性化用户认证流程二_第9张图片





index


   

index

spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/imooc-demo?useUnicode=yes&characterEncoding=UTF-8
spring.datasource.username = root
spring.datasource.password = 123456

spring.session.store-type = none

#security.basic.enabled = false

server.port = 8060

imooc.security.browser.loginPage=/demo-signIn.html
imooc.security.browser.loginType=REDIRECT

访问index.html 密码正确和失败都试一次看是否还是json:

security个性化用户认证流程二_第10张图片

security个性化用户认证流程二_第11张图片

security个性化用户认证流程二_第12张图片

bye bye!

你可能感兴趣的:(JAVA知识)