xufenglei
2018-01-04 06f0cb55c5ac3e43e3a7a1934fc566c5c8adf400
token 相关
3 files added
3 files modified
199 ■■■■■ changed files
src/main/java/com/moral/controller/TokenControllers.java 48 ●●●●● patch | view | raw | blame | history
src/main/java/com/moral/security/AuthorizationServerConfiguration.java 9 ●●●● patch | view | raw | blame | history
src/main/java/com/moral/security/ResourceServerConfiguration.java 18 ●●●●● patch | view | raw | blame | history
src/main/java/com/moral/security/WebSecurityConfiguration.java 3 ●●●● patch | view | raw | blame | history
src/main/java/com/moral/service/TokenService.java 11 ●●●●● patch | view | raw | blame | history
src/main/java/com/moral/service/impl/TokenServiceImpl.java 110 ●●●●● patch | view | raw | blame | history
src/main/java/com/moral/controller/TokenControllers.java
New file
@@ -0,0 +1,48 @@
package com.moral.controller;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import com.moral.service.TokenService;
@RestController
public class TokenControllers {
    @Resource
    private TokenService tokenService;
    @GetMapping("oauth/token/{type}/{username}/{password}")
    public Map<String, Object> getAuthToken(@PathVariable("username") String username,
            @PathVariable("password") String password, @PathVariable("type") String type, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();
        if (ObjectUtils.isEmpty(username) || ObjectUtils.isEmpty(password) || ObjectUtils.isEmpty(type)) {
            result.put("msg", "参数输入不合法");
        } else {
            String url = request.getRequestURL().toString().replace(request.getRequestURI(), "") + request.getContextPath();
            String realPath = request.getServletContext().getRealPath("/");
            result = tokenService.getAuthToken(type, username, password, url);
        }
        return result;
    }
    @PostMapping("oauth/token/{refresh_token}")
    public Map<String, Object> getAuthToken(@PathVariable("refresh_token") String refresh_token,HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();
        if (ObjectUtils.isEmpty(refresh_token)) {
            result.put("msg", "参数输入不合法");
        } else {
            String url = request.getRequestURL().toString().replace(request.getRequestURI(), "") + request.getContextPath();
            result = tokenService.getAuthToken(refresh_token, url);
        }
        return result;
    }
}
src/main/java/com/moral/security/AuthorizationServerConfiguration.java
@@ -4,6 +4,7 @@
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
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;
@@ -17,6 +18,9 @@
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
    private static String REALM = "MY_OAUTH_REALM";
    @Autowired
    private UserDetailsService userDetailsService;
    
    @Autowired
    private TokenStore tokenStore;
@@ -43,7 +47,10 @@
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler).authenticationManager(authenticationManager);
        endpoints.tokenStore(tokenStore)
        .userApprovalHandler(userApprovalHandler)
        .authenticationManager(authenticationManager)
        .userDetailsService(userDetailsService);
    }
    @Override
src/main/java/com/moral/security/ResourceServerConfiguration.java
@@ -27,5 +27,23 @@
                .authorizeRequests()
                .antMatchers("/test/**").permitAll()
                .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
        /*http.requestMatchers()
        .antMatchers("/screen/**")
        .and()
        .authorizeRequests()
        .antMatchers("/screen/**").permitAll()
        .and()
        .exceptionHandling()
        .accessDeniedHandler(new OAuth2AccessDeniedHandler());*/
        /*http.requestMatchers()
        .antMatchers("/mobile/**")
        .and()
        .authorizeRequests()
        .antMatchers("/mobile/**").permitAll()
        .and()
        .exceptionHandling()
        .accessDeniedHandler(new OAuth2AccessDeniedHandler());*/
    }
}
src/main/java/com/moral/security/WebSecurityConfiguration.java
@@ -14,6 +14,7 @@
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenApprovalStore;
@@ -44,7 +45,7 @@
                .withUser("bill").password("abc123").roles("ADMIN").and()
                .withUser("bob").password("abc123").roles("USER");
//        auth.userDetailsService(userDetailsService).passwordEncoder(new Md5PasswordEncoder());
        auth.userDetailsService(userDetailsService).passwordEncoder(NoOpPasswordEncoder.getInstance());
    }
    @Override
src/main/java/com/moral/service/TokenService.java
New file
@@ -0,0 +1,11 @@
package com.moral.service;
import java.util.Map;
public interface TokenService {
    Map<String, Object> getAuthToken(String type, String username, String password, String url);
    Map<String, Object> getAuthToken(String token, String url);
}
src/main/java/com/moral/service/impl/TokenServiceImpl.java
New file
@@ -0,0 +1,110 @@
package com.moral.service.impl;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.codec.binary.Base64;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;
import com.moral.common.bean.Constants;
import com.moral.common.util.Crypto;
import com.moral.common.util.RedisUtil;
import com.moral.entity.Account;
import com.moral.entity.OperateUser;
import com.moral.service.AccountService;
import com.moral.service.OperateUserService;
import com.moral.service.TokenService;
@Service
@SuppressWarnings({ "unchecked", "rawtypes" })
public class TokenServiceImpl implements TokenService {
    private static final String AUTH_SERVER_URI = "/oauth/token?grant_type=password&username={username}&password={password}";
    private static final String REFRESH_SERVER_URI = "/oauth/token?grant_type=refresh_token&refresh_token={refresh_token}";
    @Resource
    private AccountService accountService;
    @Resource
    private OperateUserService operateUserService;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Override
    public Map<String, Object> getAuthToken(String type, String username, String password, String url) {
        Map<String, Object> result = new HashMap<String, Object>();
        password = Crypto.md5(password);
        if ("screen".equals(type)) {
            Account account = accountService.getAccountByAccountName(username);
            if (ObjectUtils.isEmpty(account)) {
                result.put("msg", "用户名输入有误");
                return result;
            } else {
                if (!password.equals(account.getPassword())) {
                    result.put("msg", "密码输入有误");
                    return result;
                }
                if (Constants.IS_DELETE_TRUE.equals(account.getIsDelete())) {
                    result.put("msg", "您的账号已禁用,请联系管理员!");
                    return result;
                }
                result.put("accountId", account.getId());
            }
        } else if ("mobile".equals(type)) {
            OperateUser operateUser = operateUserService.getOperateUserByMobile(username);
            if (ObjectUtils.isEmpty(operateUser)) {
                result.put("msg", "用户名输入有误");
                return result;
            } else {
                if (!password.equals(operateUser.getPassword())) {
                    result.put("msg", "密码输入有误");
                    return result;
                }
                result.put("userId", operateUser.getId());
            }
        } else {
            result.put("msg", "类型输入有误");
            return result;
        }
        RedisUtil.set(redisTemplate, "token_" + username, type);
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<String> httpEntity = new HttpEntity<String>(getHeadersWithClientCredentials());
        Map map = restTemplate.postForObject(url + AUTH_SERVER_URI, httpEntity, Map.class, username, password);
        result.putAll(map);
        return result;
    }
    @Override
    public Map<String, Object> getAuthToken(String refresh_token, String url) {
        HttpEntity<String> httpEntity = new HttpEntity<String>(getHeadersWithClientCredentials());
        RestTemplate restTemplate = new RestTemplate();
        Map map = restTemplate.postForObject(url + REFRESH_SERVER_URI, httpEntity, Map.class, refresh_token);
        return map;
    }
    private static HttpHeaders getHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        return headers;
    }
    private static HttpHeaders getHeadersWithClientCredentials() {
        String plainClientCredentials = "my-trusted-client:secret";
        String base64ClientCredentials = new String(Base64.encodeBase64(plainClientCredentials.getBytes()));
        HttpHeaders headers = getHeaders();
        headers.add("Authorization", "Basic " + base64ClientCredentials);
        return headers;
    }
}