特別注意:以下內(nèi)容如果訪問失敗或有其他疑問,可先學(xué)習(xí):
SpringSecurity +oauth2+JWT實現(xiàn)統(tǒng)一授權(quán)和認證及項目搭建(一)
1 獲取當(dāng)前用戶的信息代碼為:
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
但是,通過運行會發(fā)現(xiàn)principal的值只是用戶名,沒有用戶信息,通過去看源碼,才發(fā)現(xiàn)問題所在,以下是源碼:
源碼類:DefaultUserAuthenticationConverter.java

通過源碼分析,發(fā)現(xiàn)這里的map只存儲用戶名,對此,如果要獲取用戶,我這里提供的方案是重寫該方法,步驟如下:
新建UserAuthenticationConverter.java配置類,繼承DefaultUserAuthenticationConverter.java,代碼如下:
package com.yty.system.oauth.config.jwt;
import com.yty.system.oauth.entity.SysUser;
import com.yty.system.oauth.entity.vo.SecurityUser;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import org.springframework.util.StringUtils;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class UserAuthenticationConverter extends DefaultUserAuthenticationConverter {
private Collection<? extends GrantedAuthority> defaultAuthorities;
public void setDefaultAuthorities(String[] defaultAuthorities) {
this.defaultAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils.arrayToCommaDelimitedString(defaultAuthorities));
}
private static final String USER_INFO = "userInfo";
/**
* 設(shè)置存入認證信息中的Map
*
* @param authentication
* @return
*/
@Override
public Map<String, ?> convertUserAuthentication(Authentication authentication) {
// 入?yún)uthentication中保存了完整的用戶信息(都已經(jīng)有完整信息了還查個P)。
Map<String, Object> map = new HashMap<>(1);
// 獲取用戶信息并保存。
Object o = authentication.getPrincipal();
SecurityUser userInfo = (SecurityUser) o;
SysUser sysUser = userInfo.getSysUser();
map.put(USER_INFO, sysUser);
// 保存了賬戶的權(quán)限信息,可以通過Authentication..getAuthorities()方法獲取。
if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
map.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
}
return map;
}
/**
* 選擇存入認證信息中的數(shù)據(jù)
*
* @param map
* @return
*/
@Override
public Authentication extractAuthentication(Map<String, ?> map) {
Authentication authentication = null;
if (map.containsKey(USER_INFO)) {
// 將用戶對象作為用戶信息。
Object principal = map.get(USER_INFO);
Collection<? extends GrantedAuthority> authorities = this.getAuthorities(map);
authentication = new UsernamePasswordAuthenticationToken(principal, "N/A", authorities);
}
return authentication;
}
private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
if (!map.containsKey(AUTHORITIES)) {
return this.defaultAuthorities;
} else {
Object authorities = map.get(AUTHORITIES);
if (authorities instanceof String) {
return AuthorityUtils.commaSeparatedStringToAuthorityList((String)authorities);
} else if (authorities instanceof Collection) {
return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils.collectionToCommaDelimitedString((Collection)authorities));
} else {
throw new IllegalArgumentException("Authorities must be either a String or a Collection");
}
}
}
}
修改JwtTokenStoreConfig.java類,將以上配置類引用到方法jwtAccessTokenConverter中,具體實現(xiàn)如下:
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
DefaultAccessTokenConverter defaultAccessTokenConverter = new DefaultAccessTokenConverter();
defaultAccessTokenConverter.setUserTokenConverter(new UserAuthenticationConverter());
// 賦予新的Token轉(zhuǎn)換器。
accessTokenConverter.setAccessTokenConverter(defaultAccessTokenConverter);
//配置JWT使用的秘鑰
accessTokenConverter.setSigningKey(secret);
return accessTokenConverter;
}
在UserDetailService編寫靜態(tài)方法getCurrentUser獲取用戶信息,代碼如下:
/**
* 獲取當(dāng)前用戶信息
*/
public static SysUser getCurrentUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (Objects.isNull(authentication)) {
throw new RuntimeException("請登錄");
}
Object principal = authentication.getPrincipal();
if (Objects.isNull(principal)) {
throw new RuntimeException("請登錄");
}
ObjectMapper objectMapper = new ObjectMapper();
SysUser sysUser = objectMapper.convertValue(principal, SysUser.class);
return sysUser;
}
在UserController.java類中編寫測試入口方法getCurrentUser,代碼如下:
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("/getCurrentUser")
public Object getCurrentUser() {
SysUser currentUser = UserDetailService.getCurrentUser();
return currentUser;
}
}
postman訪問:
1 先獲取token

2 調(diào)用接口http://localhost:8500/oauth_api/user/getCurrentUser,注意參數(shù),需要在請求頭中添加參數(shù)Authorization,內(nèi)容為:oken_type+空格+access_token,如圖所示:文章來源:http://www.zghlxwxcb.cn/news/detail-411501.html

注意,如果訪問不通過,需要在資源配置類中將用戶訪問接口添加到資源配置ResourceServiceConfig.java中,如無該類,自己新建一個,代碼如下所示:文章來源地址http://www.zghlxwxcb.cn/news/detail-411501.html
package com.yty.system.oauth.config.jwt;
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;
@Configuration
@EnableResourceServer
public class ResourceServiceConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
// 受保護的資源
.and().requestMatchers()
.antMatchers("/user/**");
}
}
到了這里,關(guān)于SpringSecurity +oauth2獲取當(dāng)前登錄用戶(二)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!