解决springcloud实际项⽬中遇到的问题
问题⼀:
在oauth2+jwt格式的鉴权授权认证token中,增加⾃定义字段并获取该字段
1.继承JwtAccessTokenConverter类,重写enhance⽅法,将userId放在jwt格式的payload中
public class UaaJwtAccessTokenConverter extends JwtAccessTokenConverter {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {        if (accessToken instanceof DefaultOAuth2AccessToken) {
Object principal = Principal();
if (principal instanceof  com.kunfei.uaa.service.dto.UserDTO) {
UserDTO user = (UserDTO) principal;
HashMap<String, Object> map = new HashMap<>();
map.put("userId", Id());
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(map);
}
}
hance(accessToken, authentication);
}
}
2.在认证服务器中,增加⾃定义的UaaJwtAccessTokenConverter类到spring上下⽂
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new UaaJwtAccessTokenConverter();
KeyPair keyPair = new KeyStoreKeyFactory(
new KeyStore().getName()),
.KeyStore().getAlias());
converter.setKeyPair(keyPair);
return converter;
}
3.获取tokne并解析token中的payload,得到userId
注⼊JwtTokenStore
@Autowired
public JwtTokenStore tokenStore;
public static Optional<Long> getCurrentUserId(JwtTokenStore tokenStore) {
SecurityContext securityContext = Context();
Authentication authentication = Authentication();
if (authentication != null) {
Object details = Details();
if (details instanceof OAuth2AuthenticationDetails) {
String userId = null;
Object decodedDetails = ((OAuth2AuthenticationDetails) details).getDecodedDetails();
if (decodedDetails != null&& decodedDetails instanceof Map) {
userId = ((Map<?, ?>) decodedDetails).get("userId").toString();
}else {
String accessToken = ((OAuth2AuthenticationDetails) details).getTokenValue();
Map<String, Object> extraInfoMap =
userId = ("userId").toString();
}
return Optional.ofNullable(Long.valueOf(userId));
}
}
return Optional.ofNullable(null);
}
问题⼆:
在Restful API接⼝中,增加过滤器,修改response中body体的内容
1.继承HttpServletResponseWrapper(HttpServletResponse的包装实现类)
public class BodyCachingHttpServletResponseWrapper extends HttpServletResponseWrapper {
private ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
private HttpServletResponse response;
private PrintWriter pwrite;
public BodyCachingHttpServletResponseWrapper(HttpServletResponse response) {
super(response);
}
public byte[] getBytes() {
if(pwrite != null) {
pwrite.close();
ByteArray();
}
if(byteArrayOutputStream != null) {
try {
byteArrayOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
ByteArray();
}
@Override
public ServletOutputStream getOutputStream() {
return new ServletOutputStreamWrapper(this.byteArrayOutputStream , sponse);
}
@Override
public PrintWriter getWriter() throws IOException {
pwrite = new PrintWriter(new OutputStreamWriter(this.byteArrayOutputStream ,
return pwrite;
}
private static class ServletOutputStreamWrapper extends ServletOutputStream {
private ByteArrayOutputStream outputStream;
private HttpServletResponse response;
public ServletOutputStreamWrapper(ByteArrayOutputStream outputStream, HttpServletResponse response) {            super();
this.outputStream = outputStream;
}springcloud难学吗
@Override
public boolean isReady() {
return true;
}
@Override
public void setWriteListener(WriteListener listener) {
}
@Override
public void write(int b) throws IOException {
this.outputStream.write(b);
}
//在原有body的基础上,提交原有的内容,先是新增⽽不是替换,需要注释掉
//        @Override
//        public void flush() throws IOException {
/
/            if (! sponse.isCommitted()) {
//                byte[] body = ByteArray();
//                ServletOutputStream outputStream = OutputStream();
//                outputStream.write(body);
//                outputStream.flush();
//            }
//        }
}
}
2.增加过滤器,替换response中body的内容
@WebFilter(filterName = "responseFilter",urlPatterns = "/*")
public class ResponseFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)            throws IOException, ServletException {
BodyCachingHttpServletResponseWrapper responseWrapper = new
BodyCachingHttpServletResponseWrapper((HttpServletResponse) servletResponse);
chain.doFilter(servletRequest, responseWrapper);
Optional<String> xTotalCount = Optional.Header("X-Total-Count"));
byte[] writeValueByte = null;
if(xTotalCount.isPresent() && Bytes() != null) {
String currentTotal = ();
String currentData = new Bytes());
String writeValue = "{\"total\":"+currentTotal+",\"data\":"+currentData+"}";
writeValueByte = Bytes();
}else {
writeValueByte = Bytes();
}
//重新写⼊输出流
ServletOutputStream outputStream = OutputStream();
outputStream.write(writeValueByte);
outputStream.flush();
outputStream.close();
}
}
3.在启动器上增加扫描servlet的注解
@ServletComponentScan

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。