SpringBoot入門建站全系列(三十五)整合Oauth2做單機版認證授權

SpringBoot入門建站全系列(三十五)整合Oauth2做單機版認證授權

一、概述

OAuth 2.0 規範定義了一個授權(delegation)協議,對於使用Web的應用程序和API在網絡上傳遞授權決策非常有用。OAuth被用在各鍾各樣的應用程序中,包括提供用戶認證的機制。

四種模式:
- 密碼模式;
- 授權碼模式;
- 簡化模式;
- 客戶端模式;
四種角色:
- 資源擁有者;
- 資源服務器;
- 第三方應用客戶端;
- 授權服務器;

本文主要說明授權碼模式。

首發地址:
  品茗IT: https://www.pomit.cn/p/2806101761026561

如果大家正在尋找一個java的學習環境,或者在開發中遇到困難,可以加入我們的java學習圈,點擊即可加入,共同學習,節約學習時間,減少很多在學習中遇到的難題。

本篇和Spring的整合Oauth2:《Spring整合Oauth2單機版認證授權詳情》並沒有多大區別,真正將Oauth2用起來做單點登錄,需要考慮的東西不止這些,這裏只是做單機演示說明,後續會在SpringCloud專題中對真實環境的單點登錄做詳細說明。

二、基本配置

2.1 Maven依賴

需要引入oauth2用到的依賴,以及數據源、mybatis依賴。

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-dbcp2</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.security.oauth</groupId>
	<artifactId>spring-security-oauth2</artifactId>
	<version>${security.oauth2.version}</version>
</dependency>

2.2 配置文件

在application.properties 中需要配置數據庫相關信息的信息,如:

spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource
spring.datasource.dbcp2.max-wait-millis=60000
spring.datasource.dbcp2.min-idle=20
spring.datasource.dbcp2.initial-size=2
spring.datasource.dbcp2.validation-query=SELECT 1
spring.datasource.dbcp2.connection-properties=characterEncoding=utf8
spring.datasource.dbcp2.validation-query=SELECT 1
spring.datasource.dbcp2.test-while-idle=true
spring.datasource.dbcp2.test-on-borrow=true
spring.datasource.dbcp2.test-on-return=false

spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/boot?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
spring.datasource.username=cff
spring.datasource.password=123456

mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

這只是數據庫的配置而已,無須oauth2的配置。

三、配置資源服務器

資源服務器需要使用@EnableResourceServer開啓,是標明哪些資源是受Ouath2保護的。下面的代碼標明/api是受保護的,而且資源id是my_rest_api。

ResourceServerConfiguration:

package com.cff.springbootwork.oauth.resource;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

	private static final String RESOURCE_ID = "my_rest_api";

	@Override
	public void configure(ResourceServerSecurityConfigurer resources) {
		resources.resourceId(RESOURCE_ID).stateless(false);
	}

	@Override
	public void configure(HttpSecurity http) throws Exception {
		http.anonymous().disable().requestMatchers().antMatchers("/api/**").and().authorizeRequests()
				.antMatchers("/api/**").authenticated().and().exceptionHandling()
				.accessDeniedHandler(new OAuth2AccessDeniedHandler());
	}

}

四、配置授權服務器

授權服務器需要使用@EnableAuthorizationServer註解開啓,主要負責client的認證,token的生成的。AuthorizationServerConfiguration需要依賴SpringSecurity的配置,因此下面還是要說SpringSecurity的配置。

4.1 授權配置

AuthorizationServerConfiguration:

package com.cff.springbootwork.oauth.auth;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.security.oauth2.provider.client.InMemoryClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;

import com.cff.springbootwork.oauth.provider.DefaultPasswordEncoder;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

	private static String REALM = "MY_OAUTH_REALM";

	@Autowired
	private AuthenticationManager authenticationManager;
	
	@Autowired
	DefaultPasswordEncoder defaultPasswordEncoder;

	@Autowired
	@Qualifier("authorizationCodeServices")
	private AuthorizationCodeServices authorizationCodeServices;

	/**
	 * 可以在這裏將客戶端數據替換成數據庫配置。
	 * 
	 * @return
	 */
	@Bean
	public ClientDetailsService clientDetailsService() {
		InMemoryClientDetailsService inMemoryClientDetailsService = new InMemoryClientDetailsService();
		BaseClientDetails baseClientDetails = new BaseClientDetails();
		baseClientDetails.setClientId("MwonYjDKBuPtLLlK");
		baseClientDetails.setClientSecret(defaultPasswordEncoder.encode("123456"));
		baseClientDetails.setAccessTokenValiditySeconds(120);
		baseClientDetails.setRefreshTokenValiditySeconds(600);
		
		Set<String> salesWords = new HashSet<String>() {{
			add("http://www.pomit.cn");
		}};
		baseClientDetails.setRegisteredRedirectUri(salesWords);
		List<String> scope = Arrays.asList("read", "write", "trust");
		baseClientDetails.setScope(scope);

		List<String> authorizedGrantTypes = Arrays.asList("authorization_code", "refresh_token");
		baseClientDetails.setAuthorizedGrantTypes(authorizedGrantTypes);

		Map<String, ClientDetails> clientDetailsStore = new HashMap<>();
		clientDetailsStore.put("MwonYjDKBuPtLLlK", baseClientDetails);
		inMemoryClientDetailsService.setClientDetailsStore(clientDetailsStore);

		return inMemoryClientDetailsService;
	}

	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		clients.withClientDetails(clientDetailsService());
	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		endpoints.authenticationManager(authenticationManager);
		endpoints.authorizationCodeServices(authorizationCodeServices);
	}

	@Override
	public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
		oauthServer.allowFormAuthenticationForClients();
		oauthServer.realm(REALM + "/client");
	}
}


這裏的

  • clientDetailsService是配置文件中配置的客戶端詳情;
  • tokenStore是token存儲bean;
  • authenticationManager安全管理器,使用Spring定義的即可,但要聲明爲bean。
  • authorizationCodeServices是配置文件中我們自定義的token生成bean。
  • PasswordEncoder密碼處理工具類,必須指定的一個bean,可以使用NoOpPasswordEncoder來表明並未對密碼做任何處理,實際上你可以實現PasswordEncoder來寫自己的密碼處理方案。
  • UserApprovalHandler 需要定義爲bean的Oauth2授權通過處理器。

4.2 密碼處理器

DefaultPasswordEncoder 負責對密碼進行轉換。

DefaultPasswordEncoder :

package com.cff.springbootwork.oauth.provider;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class DefaultPasswordEncoder implements PasswordEncoder {

	public DefaultPasswordEncoder() {
		this(-1);
	}

	/**
	 * @param strength
	 *            the log rounds to use, between 4 and 31
	 */
	public DefaultPasswordEncoder(int strength) {

	}

	public String encode(CharSequence rawPassword) {
		return rawPassword.toString();
	}

	public boolean matches(CharSequence rawPassword, String encodedPassword) {
		return rawPassword.toString().equals(encodedPassword);
	}
}

4.3 自定義的Token的Code生成邏輯

這個就是定義在授權服務器AuthorizationServerConfiguration 中的authorizationCodeServices。

InMemoryAuthorizationCodeServices:

package com.cff.springbootwork.oauth.token;

import java.util.concurrent.ConcurrentHashMap;

import org.springframework.security.oauth2.common.util.RandomValueStringGenerator;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
import org.springframework.stereotype.Service;

@Service("authorizationCodeServices")
public class InMemoryAuthorizationCodeServices extends RandomValueAuthorizationCodeServices {
	protected final ConcurrentHashMap<String, OAuth2Authentication> authorizationCodeStore = new ConcurrentHashMap<String, OAuth2Authentication>();
	private RandomValueStringGenerator generator = new RandomValueStringGenerator(16);

	@Override
	protected void store(String code, OAuth2Authentication authentication) {
		this.authorizationCodeStore.put(code, authentication);
	}

	@Override
	public OAuth2Authentication remove(String code) {
		OAuth2Authentication auth = this.authorizationCodeStore.remove(code);
		return auth;
	}

	@Override
	public String createAuthorizationCode(OAuth2Authentication authentication) {
		String code = generator.generate();
		store(code, authentication);
		return code;
	}
}

五、SpringSecurity配置

5.1 SpringSecurity常規配置

SpringSecurity的配置在客戶端和認證授權服務器中是必須的,這裏是單機,它更是必須的。

ClientSecurityConfiguration:

package com.cff.springbootwork.oauth.client;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import com.cff.springbootwork.oauth.handler.AjaxAuthFailHandler;
import com.cff.springbootwork.oauth.handler.AjaxAuthSuccessHandler;
import com.cff.springbootwork.oauth.handler.AjaxLogoutSuccessHandler;
import com.cff.springbootwork.oauth.handler.UnauthorizedEntryPoint;
import com.cff.springbootwork.oauth.provider.SimpleAuthenticationProvider;

@Configuration
@EnableWebSecurity
public class ClientSecurityConfiguration extends WebSecurityConfigurerAdapter {
	@Autowired
	private SimpleAuthenticationProvider simpleAuthenticationProvider;

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth.authenticationProvider(simpleAuthenticationProvider);
	}

	@Override
	public void configure(HttpSecurity http) throws Exception {
		SimpleUrlAuthenticationFailureHandler hander = new SimpleUrlAuthenticationFailureHandler();
		hander.setUseForward(true);
		hander.setDefaultFailureUrl("/login.html");

		http.exceptionHandling().authenticationEntryPoint(new UnauthorizedEntryPoint()).and().csrf().disable()
				.authorizeRequests().antMatchers("/oauth/**").permitAll().antMatchers("/mybatis/**").authenticated()
				.and().formLogin().loginPage("/login.html").usernameParameter("userName").passwordParameter("userPwd")
				.loginProcessingUrl("/login").successHandler(new AjaxAuthSuccessHandler())
				.failureHandler(new AjaxAuthFailHandler()).and().logout().logoutUrl("/logout")
				.logoutSuccessHandler(new AjaxLogoutSuccessHandler());

		http.authorizeRequests().antMatchers("/user/**").authenticated();
	}

	@Override
	@Bean
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
	}
}


這裏,

  • SimpleAuthenticationProvider 是用戶名密碼認證處理器。下面會說。

  • authenticationManager安全管理器,使用Spring定義的即可,但要聲明爲bean。

  • configure方法是SpringSecurity配置的常規寫法。

  • UnauthorizedEntryPoint:未授權的統一處理方式。

  • successHandler、failureHandler、logoutSuccessHandler顧名思義,就是響應處理邏輯,如果不打算單獨處理,只做跳轉,有響應的successForwardUrl、failureForwardUrl、logoutSuccessUrl等。

5.2 SpringSecurity用戶名密碼驗證器

SimpleAuthenticationProvider 實現了AuthenticationProvider 接口的authenticate方法,提供用戶名密碼的校驗,校驗成功後,生成UsernamePasswordAuthenticationToken。

這裏面用到的userInfoService,是自己實現從數據庫中獲取用戶信息的業務邏輯。

SimpleAuthenticationProvider :

package com.cff.springbootwork.oauth.provider;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Component;

import com.cff.springbootwork.mybatis.domain.UserInfo;
import com.cff.springbootwork.mybatis.service.UserInfoService;

@Component
public class SimpleAuthenticationProvider implements AuthenticationProvider {
	@Autowired
	private UserInfoService userInfoService;

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		
		String userName = authentication.getPrincipal().toString();
		UserInfo user = userInfoService.getUserInfoByUserName(userName);

		if (user == null) {
			throw new BadCredentialsException("查無此用戶");
		}
		if (user.getPasswd() != null && user.getPasswd().equals(authentication.getCredentials())) {
			Collection<? extends GrantedAuthority> authorities = AuthorityUtils.NO_AUTHORITIES;

			return new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPasswd(), authorities);
		} else {
			throw new BadCredentialsException("用戶名或密碼錯誤。");
		}
	}

	@Override
	public boolean supports(Class<?> arg0) {
		return true;
	}

}


六、測試Oauth2

6.1 Web測試接口

OauthRest :


package com.cff.springbootwork.oauth.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.cff.springbootwork.mybatis.domain.UserInfo;
import com.cff.springbootwork.mybatis.service.UserInfoService;

@RestController
@RequestMapping("/api")
public class OauthRest {

	@Autowired
	UserInfoService userInfoService;

	@RequestMapping(value = "/page", method = { RequestMethod.GET })
	public List<UserInfo> page() {
		return userInfoService.page(1, 10);
	}

}

6.2 測試過程

  1. 首先訪問http://127.0.0.1:8080/api/test。 提示
<oauth>
<error_description>
An Authentication object was not found in the SecurityContext
</error_description>
<error>unauthorized</error>
</oauth>

這標明,oauth2控制了資源,需要access_token。

  1. 請求授權接口oauth/authorize:http://localhost:8080/oauth/authorize?response_type=code&client_id=MwonYjDKBuPtLLlK&redirect_uri=http://www.pomit.cn

client_id是配置文件中寫的,redirect_uri隨意,因爲單機版的只是測試接口。後面會整理下多機版的博文。

打開後自動調整到登錄頁面:

在這裏插入圖片描述

輸入正確的用戶名密碼,調整到授權頁面。

在這裏插入圖片描述

點擊同意以後,調整到redirect_uri指定的頁面。

在這裏插入圖片描述

獲取到code:TnSFA6vrIZiKadwr

  1. 用code換取access_token,請求token接口:http://127.0.0.1:8080/oauth/token?grant_type=authorization_code&code=TnSFA6vrIZiKadwr&client_id=MwonYjDKBuPtLLlK&client_secret=secret&redirect_uri=http://www.pomit.cn。這個請求必須是post,因此不能在瀏覽器中輸入了,可以使用postman:

在這裏插入圖片描述

獲取到access_token爲:686dc5d5-60e9-48af-bba7-7f16b49c248b。

  1. 用access_token請求/api/test接口:

http://127.0.0.1:8080/api/test?access_token=686dc5d5-60e9-48af-bba7-7f16b49c248b結果爲:

在這裏插入圖片描述

七、過程中用到的其他實體及邏輯

AjaxAuthFailHandler:

package com.cff.springbootwork.oauth.handler;

import java.io.IOException;

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

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import com.cff.springbootwork.oauth.model.ResultCode;
import com.cff.springbootwork.oauth.model.ResultModel;
import com.fasterxml.jackson.databind.ObjectMapper;

public class AjaxAuthFailHandler extends SimpleUrlAuthenticationFailureHandler {
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		if (isAjaxRequest(request)) {
			ResultModel rm = new ResultModel(ResultCode.CODE_00014.getCode(), exception.getMessage());
			ObjectMapper mapper = new ObjectMapper();
			response.setStatus(HttpStatus.OK.value());
			response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
			mapper.writeValue(response.getWriter(), rm);
		} else {
			setDefaultFailureUrl("/login.html");
			super.onAuthenticationFailure(request, response, exception);
		}
	}

	public static boolean isAjaxRequest(HttpServletRequest request) {
		String ajaxFlag = request.getHeader("X-Requested-With");
		return ajaxFlag != null && "XMLHttpRequest".equals(ajaxFlag);
	}
}

AjaxAuthSuccessHandler:

package com.cff.springbootwork.oauth.handler;

import java.io.IOException;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import com.cff.springbootwork.oauth.model.ResultCode;
import com.cff.springbootwork.oauth.model.ResultModel;
import com.fasterxml.jackson.databind.ObjectMapper;

public class AjaxAuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
	protected final Log logger = LogFactory.getLog(this.getClass());

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		request.getSession().setAttribute("userName", authentication.getName());
		if (isAjaxRequest(request)) {
			ResultModel rm = new ResultModel(ResultCode.CODE_00000);
			ObjectMapper mapper = new ObjectMapper();
			response.setStatus(HttpStatus.OK.value());
			response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
			mapper.writeValue(response.getWriter(), rm);
		} else {
			super.onAuthenticationSuccess(request, response, authentication);
		}
	}

	public static boolean isAjaxRequest(HttpServletRequest request) {
		String ajaxFlag = request.getHeader("X-Requested-With");
		return ajaxFlag != null && "XMLHttpRequest".equals(ajaxFlag);
	}
}


AjaxLogoutSuccessHandler:

package com.cff.springbootwork.oauth.handler;

import java.io.IOException;

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

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;

import com.cff.springbootwork.oauth.model.ResultCode;
import com.cff.springbootwork.oauth.model.ResultModel;
import com.fasterxml.jackson.databind.ObjectMapper;

public class AjaxLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
	public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		if (isAjaxRequest(request)) {
			ResultModel rm = new ResultModel(ResultCode.CODE_00000);
			ObjectMapper mapper = new ObjectMapper();
			response.setStatus(HttpStatus.OK.value());
			response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
			mapper.writeValue(response.getWriter(), rm);
		} else {
			super.onLogoutSuccess(request, response, authentication);
		}
	}

	public static boolean isAjaxRequest(HttpServletRequest request) {
		String ajaxFlag = request.getHeader("X-Requested-With");
		return ajaxFlag != null && "XMLHttpRequest".equals(ajaxFlag);
	}
}

UnauthorizedEntryPoint:

package com.cff.springbootwork.oauth.handler;

import java.io.IOException;

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

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import com.cff.springbootwork.oauth.model.ResultCode;
import com.cff.springbootwork.oauth.model.ResultModel;
import com.fasterxml.jackson.databind.ObjectMapper;

public class UnauthorizedEntryPoint implements AuthenticationEntryPoint {
	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authException) throws IOException, ServletException {
		if (isAjaxRequest(request)) {
			ResultModel rm = new ResultModel(ResultCode.CODE_40004);
			ObjectMapper mapper = new ObjectMapper();
			response.setStatus(HttpStatus.OK.value());
			response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
			mapper.writeValue(response.getWriter(), rm);
		} else {
			response.sendRedirect("/login.html");
		}

	}

	public static boolean isAjaxRequest(HttpServletRequest request) {
		String ajaxFlag = request.getHeader("X-Requested-With");
		return ajaxFlag != null && "XMLHttpRequest".equals(ajaxFlag);
	}
}

ResultModel:

package com.cff.springbootwork.oauth.model;

public class ResultModel {
	String code;
	String message;

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public ResultModel() {
	}

	public ResultModel(String code, String messgae) {
		this.code = code;
		this.message = messgae;
	}

	public ResultModel(String messgae) {
		this.code = "00000";
		this.message = messgae;
	}

	public static ResultModel ok(String messgae) {
		return new ResultModel("00000", messgae);
	}
}

八、Mybatis的邏輯及實體

UserInfoService:

package com.cff.springbootwork.mybatis.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cff.springbootwork.mybatis.dao.UserInfoDao;
import com.cff.springbootwork.mybatis.domain.UserInfo;

@Service
public class UserInfoService {
	@Autowired
	UserInfoDao userInfoDao;
	public UserInfo getUserInfoByUserName(String userName){
		return userInfoDao.findByUserName(userName);
	}
	
	public List<UserInfo> page(int page, int size){
		return userInfoDao.testPageSql(page, size);
	}
	
	public List<UserInfo> testTrimSql(UserInfo userInfo){
		return userInfoDao.testTrimSql(userInfo);
	}
}

UserInfoMapper:

package com.cff.springbootwork.mybatis.dao;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.cff.springbootwork.mybatis.domain.UserInfo;

@Mapper
public interface UserInfoDao {
	@Select({
		"<script>",
	        "SELECT ",
	        "user_name as userName,passwd,name,mobile,valid, user_type as userType",
	        "FROM user_info",
	        "WHERE user_name = #{userName,jdbcType=VARCHAR}",
	   "</script>"})
	UserInfo findByUserName(@Param("userName") String userName);
	
	@Select({
		"<script>",
	        "SELECT ",
	        "user_name as userName,passwd,name,mobile,valid, user_type as userType",
	        "FROM user_info",
	        "WHERE mobile = #{mobile,jdbcType=VARCHAR}",
            "<if test='userType != null and userType != \"\" '> and user_type = #{userType, jdbcType=VARCHAR} </if>",
	   "</script>"})
	List<UserInfo> testIfSql(@Param("mobile") String mobile,@Param("userType") String userType);
	
	@Select({
		"<script>",
			"SELECT ",
	        "user_name as userName,passwd,name,mobile,valid, user_type as userType",
	         "     FROM user_info ",
	         "    WHERE mobile IN (",
	         "   <foreach collection = 'mobileList' item='mobileItem' index='index' separator=',' >",
	         "      #{mobileItem}",
	         "   </foreach>",
	         "   )",
	    "</script>"})
	List<UserInfo> testForeachSql(@Param("mobileList") List<String> mobile);
	
	@Update({
		"<script>",
			"	UPDATE user_info",
	        "   SET ",
			"	<choose>",
			"	<when test='userType!=null'> user_type=#{user_type, jdbcType=VARCHAR} </when>",
			"	<otherwise> user_type='0000' </otherwise>",
			"	</choose>",
	        "  	WHERE user_name = #{userName, jdbcType=VARCHAR}",
	  	"</script>" })
	int testUpdateWhenSql(@Param("userName") String userName,@Param("userType") String userType);
	
	@Select({
		"<script>",
	 		"<bind name=\"tableName\" value=\"item.getIdentifyTable()\" />",
	 		"SELECT ",
	        "user_name as userName,passwd,name,mobile,valid, user_type as userType",
	        "FROM ${tableName}",
	        "WHERE mobile = #{item.mobile,jdbcType=VARCHAR}",
	   "</script>"})
	public List<UserInfo> testBindSql(@Param("item") UserInfo userInfo);
	
	@Select({
		"<script>",
	 		"<bind name=\"startNum\" value=\"page*pageSize\" />",
	 		"SELECT ",
	        "user_name as userName,passwd,name,mobile,valid, user_type as userType",
	        "FROM user_info",
	        "ORDER BY mobile ASC",
	        "LIMIT #{pageSize} OFFSET #{startNum}",
	   "</script>"})
	public List<UserInfo> testPageSql(@Param("page") int page, @Param("pageSize") int size);
	
	@Select({
		"<script>",
	 		"SELECT ",
	        "user_name as userName,passwd,name,mobile,valid, user_type as userType",
	        "FROM user_info",
	        "<trim prefix=\" where \" prefixOverrides=\"AND\">",
            	"<if test='item.userType != null and item.userType != \"\" '> and user_type = #{item.userType, jdbcType=VARCHAR} </if>",
            	"<if test='item.mobile != null and item.mobile != \"\" '> and mobile = #{item.mobile, jdbcType=VARCHAR} </if>",
	        "</trim>",
	   "</script>"})
	public List<UserInfo> testTrimSql(@Param("item") UserInfo userInfo);
	
	@Update({
		"<script>",
			"	UPDATE user_info",
	        "   <set> ",
	        "<if test='item.userType != null and item.userType != \"\" '>user_type = #{item.userType, jdbcType=VARCHAR}, </if>",
        	"<if test='item.mobile != null and item.mobile != \"\" '> mobile = #{item.mobile, jdbcType=VARCHAR} </if>",
			" 	</set>",
	        "  	WHERE user_name = #{item.userName, jdbcType=VARCHAR}",
	  	"</script>" })
	public int testSetSql(@Param("item") UserInfo userInfo);
}


UserInfo:

package com.cff.springbootwork.mybatis.domain;

public class UserInfo {
	private String userName;
	private String passwd;
	private String name;
	private String mobile;
	private Integer valid;
	private String userType;

	public UserInfo() {

	}

	public UserInfo(UserInfo src) {
		this.userName = src.userName;
		this.passwd = src.passwd;
		this.name = src.name;
		this.mobile = src.mobile;
		this.valid = src.valid;
	}

	public UserInfo(String userName, String passwd, String name, String mobile, Integer valid) {
		super();
		this.userName = userName;
		this.passwd = passwd;
		this.name = name;
		this.mobile = mobile;
		this.valid = valid;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserName() {
		return userName;
	}

	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}

	public String getPasswd() {
		return passwd;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	public String getMobile() {
		return mobile;
	}

	public void setValid(Integer valid) {
		this.valid = valid;
	}

	public Integer getValid() {
		return valid;
	}

	public String getUserType() {
		return userType;
	}

	public void setUserType(String userType) {
		this.userType = userType;
	}

	public String getIdentifyTable(){
		return "user_info";
	}
}

品茗IT-博客專題:https://www.pomit.cn/lecture.html彙總了Spring專題Springboot專題SpringCloud專題web基礎配置專題。

快速構建項目

Spring項目快速開發工具:

一鍵快速構建Spring項目工具

一鍵快速構建SpringBoot項目工具

一鍵快速構建SpringCloud項目工具

一站式Springboot項目生成

Mysql一鍵生成Mybatis註解Mapper

Spring組件化構建

SpringBoot組件化構建

SpringCloud服務化構建

喜歡這篇文章麼,喜歡就加入我們一起討論Java Web吧!
品茗IT交流羣

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章