SpringBoot入門建站全系列(三十五)整合Oauth2做單機版認證授權(quán)
一木人、概述
OAuth 2.0 規(guī)范定義了一個授權(quán)(delegation)協(xié)議,對于使用Web的應用程序和API在網(wǎng)絡(luò)上傳遞授權(quán)決策非常有用进鸠。OAuth被用在各鐘各樣的應用程序中稠曼,包括提供用戶認證的機制。
四種模式:
- 密碼模式客年;
- 授權(quán)碼模式霞幅;
- 簡化模式;
- 客戶端模式量瓜;
四種角色:
- 資源擁有者司恳;
- 資源服務(wù)器;
- 第三方應用客戶端绍傲;
- 授權(quán)服務(wù)器扔傅;
本文主要說明授權(quán)碼模式。
首發(fā)地址:
??品茗IT: https://www.pomit.cn/p/2806101761026561
如果大家正在尋找一個java的學習環(huán)境烫饼,或者在開發(fā)中遇到困難猎塞,可以加入我們的java學習圈,點擊即可加入枫弟,共同學習邢享,節(jié)約學習時間,減少很多在學習中遇到的難題淡诗。
本篇和Spring的整合Oauth2:《Spring整合Oauth2單機版認證授權(quán)詳情》并沒有多大區(qū)別骇塘,真正將Oauth2用起來做單點登錄,需要考慮的東西不止這些韩容,這里只是做單機演示說明款违,后續(xù)會在SpringCloud專題中對真實環(huán)境的單點登錄做詳細說明。
二群凶、基本配置
2.1 Maven依賴
需要引入oauth2用到的依賴插爹,以及數(shù)據(jù)源、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 中需要配置數(shù)據(jù)庫相關(guān)信息的信息赠尾,如:
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
這只是數(shù)據(jù)庫的配置而已力穗,無須oauth2的配置。
三气嫁、配置資源服務(wù)器
資源服務(wù)器需要使用@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());
}
}
四、配置授權(quán)服務(wù)器
授權(quán)服務(wù)器需要使用@EnableAuthorizationServer注解開啟梯影,主要負責client的認證巫员,token的生成的。AuthorizationServerConfiguration需要依賴SpringSecurity的配置甲棍,因此下面還是要說SpringSecurity的配置简识。
4.1 授權(quán)配置
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;
/**
* 可以在這里將客戶端數(shù)據(jù)替換成數(shù)據(jù)庫配置。
*
* @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來表明并未對密碼做任何處理,實際上你可以實現(xiàn)PasswordEncoder來寫自己的密碼處理方案司致。
- UserApprovalHandler 需要定義為bean的Oauth2授權(quán)通過處理器拆吆。
4.2 密碼處理器
DefaultPasswordEncoder 負責對密碼進行轉(zhuǎn)換。
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生成邏輯
這個就是定義在授權(quán)服務(wù)器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常規(guī)配置
SpringSecurity的配置在客戶端和認證授權(quán)服務(wù)器中是必須的,這里是單機庭再,它更是必須的捞奕。
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配置的常規(guī)寫法筏养。
UnauthorizedEntryPoint:未授權(quán)的統(tǒng)一處理方式。
successHandler常拓、failureHandler渐溶、logoutSuccessHandler顧名思義,就是響應處理邏輯墩邀,如果不打算單獨處理掌猛,只做跳轉(zhuǎn),有響應的successForwardUrl眉睹、failureForwardUrl、logoutSuccessUrl等废膘。
5.2 SpringSecurity用戶名密碼驗證器
SimpleAuthenticationProvider 實現(xiàn)了AuthenticationProvider 接口的authenticate方法竹海,提供用戶名密碼的校驗,校驗成功后丐黄,生成UsernamePasswordAuthenticationToken斋配。
這里面用到的userInfoService,是自己實現(xiàn)從數(shù)據(jù)庫中獲取用戶信息的業(yè)務(wù)邏輯灌闺。
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 測試過程
- 首先訪問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蕉斜。
- 請求授權(quán)接口oauth/authorize:
http://localhost:8080/oauth/authorize?response_type=code&client_id=MwonYjDKBuPtLLlK&redirect_uri=http://www.pomit.cn
client_id是配置文件中寫的逾柿,redirect_uri隨意,因為單機版的只是測試接口宅此。后面會整理下多機版的博文。
打開后自動調(diào)整到登錄頁面:
輸入正確的用戶名密碼弱匪,調(diào)整到授權(quán)頁面璧亮。
點擊同意以后萧诫,調(diào)整到redirect_uri指定的頁面杜顺。
獲取到code:TnSFA6vrIZiKadwr
- 用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淹禾。
- 用access_token請求/api/test接口:
http://127.0.0.1:8080/api/test?access_token=686dc5d5-60e9-48af-bba7-7f16b49c248b
結(jié)果為:
七铃岔、過程中用到的其他實體及邏輯
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基礎(chǔ)配置專題歧斟。
快速構(gòu)建項目
Spring項目快速開發(fā)工具:
喜歡這篇文章么静袖,喜歡就加入我們一起討論Java Web吧俊扭!