BaseAuthenticationSuccessHandler.java 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. /**
  2. *
  3. */
  4. package com.yihu.base.security.hander;
  5. import com.fasterxml.jackson.databind.ObjectMapper;
  6. import com.yihu.base.security.rbas.ClientServiceProvider;
  7. import org.apache.commons.codec.binary.StringUtils;
  8. import org.apache.commons.collections.MapUtils;
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.beans.factory.annotation.Qualifier;
  13. import org.springframework.security.authentication.BadCredentialsException;
  14. import org.springframework.security.core.Authentication;
  15. import org.springframework.security.crypto.codec.Base64;
  16. import org.springframework.security.oauth2.common.OAuth2AccessToken;
  17. import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException;
  18. import org.springframework.security.oauth2.provider.*;
  19. import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
  20. import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
  21. import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
  22. import org.springframework.stereotype.Component;
  23. import javax.annotation.Resource;
  24. import javax.servlet.ServletException;
  25. import javax.servlet.http.HttpServletRequest;
  26. import javax.servlet.http.HttpServletResponse;
  27. import java.io.IOException;
  28. import java.io.UnsupportedEncodingException;
  29. /**
  30. * @author chenweida
  31. * <p>
  32. * 账号密码提交需要在 head 中添加 Basic clientID:cliengSecurty
  33. */
  34. @Component("BaseAuthenticationSuccessHandler")
  35. public class BaseAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
  36. private Logger logger = LoggerFactory.getLogger(getClass());
  37. @Autowired
  38. private ObjectMapper objectMapper;
  39. @Autowired
  40. private ClientServiceProvider clientDetailsService;
  41. @Autowired
  42. private AuthorizationServerTokenServices defaultTokenServices;
  43. public BaseAuthenticationSuccessHandler() {
  44. System.out.println(clientDetailsService);
  45. }
  46. /*
  47. * (non-Javadoc)
  48. *
  49. * @see org.springframework.security.web.authentication.
  50. * AuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.
  51. * HttpServletRequest, javax.servlet.http.HttpServletResponse,
  52. * org.springframework.security.core.Authentication)
  53. */
  54. @Override
  55. public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
  56. Authentication authentication) throws IOException, ServletException {
  57. String header = request.getHeader("Authorization");
  58. if (org.springframework.util.StringUtils.isEmpty(header) || (!header.startsWith("Basic "))) {
  59. throw new UnapprovedClientAuthenticationException("请求头没有client信息");
  60. }
  61. //解析头部的basic信息
  62. String[] tokens = extractAndDecodeHeader(header, request);
  63. assert tokens.length == 2;
  64. String clientId = tokens[0];
  65. String clientSecurity = tokens[1];
  66. //得到ClientDetails
  67. ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
  68. if (clientDetails == null) {
  69. throw new UnapprovedClientAuthenticationException("clientId不存在 client:" + clientId);
  70. } else if (!StringUtils.equals(clientDetails.getClientSecret(), clientSecurity)) {
  71. throw new UnapprovedClientAuthenticationException("clientSecurity 不匹配 client:" + clientId);
  72. }
  73. TokenRequest tokenRequest = new TokenRequest(MapUtils.EMPTY_MAP, clientId, clientDetails.getScope(), "custom_password");
  74. OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
  75. OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
  76. OAuth2AccessToken token = defaultTokenServices.createAccessToken(oAuth2Authentication);
  77. response.setContentType("application/json;charset=UTF-8");
  78. response.getWriter().write(objectMapper.writeValueAsString(token));
  79. }
  80. /**
  81. * 解析
  82. *
  83. * @param header
  84. * @param request
  85. * @return
  86. * @throws IOException
  87. */
  88. private String[] extractAndDecodeHeader(String header, HttpServletRequest request)
  89. throws IOException {
  90. byte[] base64Token = header.substring(6).getBytes("UTF-8");
  91. byte[] decoded;
  92. try {
  93. decoded = Base64.decode(base64Token);
  94. } catch (IllegalArgumentException e) {
  95. throw new BadCredentialsException(
  96. "Failed to decode basic authentication token");
  97. }
  98. String token = new String(decoded, "UTF-8");
  99. int delim = token.indexOf(":");
  100. if (delim == -1) {
  101. throw new BadCredentialsException("Basic 信息不合法");
  102. }
  103. return new String[]{token.substring(0, delim), token.substring(delim + 1)};
  104. }
  105. public static void main(String[] args) throws UnsupportedEncodingException {
  106. System.out.println(new String(Base64.encode("cwd:cwd".getBytes()), "UTF-8"));// Y3dkOmN3ZA==
  107. }
  108. }