生成不带用户名和密码的访问令牌和刷新令牌

时间:2019-01-29 09:38:37

标签: spring-boot spring-security spring-security-oauth2

我正在使用springboot2在spring-security中实现oauth2。

我仅使用spring-security对用户进行身份验证,并使用用户名和密码返回用户Object。 (http://localhost:8181/login

在这里,可能有多个用户使用同一封邮件。所以再次从我得到的用户对象中获取用户ID并发送到(http://localhost:8181/oauth/token

在这里,我只想再次传递grant_type和userId而不传递用户名和密码,以便使用oauth2生成访问令牌和刷新令牌。

我该如何做到这一点。

我可以从先前的请求中获取用户名和密码吗?以及如何在oauth2中进行配置以满足我的要求。

请帮助。

在下面的代码中,我通过保持限制1来对一个用户进行身份验证,之后我将使用相同的邮件ID来获取所有用户。所有人的密码都一样。

@Override
    @Transactional
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        User user = new User();

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();

        String stringuserId = request.getParameter("userId");
        Long userId = 0L;
        try {
            if (stringuserId != null) {
                userId = Long.parseLong(stringuserId);
                System.out.println(userId);
                System.out.println(request.getParameter("username"));
                user = userRepository.findByUserId(userId).orElseThrow(
                        () -> new UsernameNotFoundException("User Not Found with -> username or email : " + email));

                System.out.println(user.toString());

                return UserPrinciple.build(user);
            } else {
                Set<GrantedAuthority> authorities = new HashSet<>();
                CustomUser userDetails = new CustomUser(email, "", authorities);


                String checkUser = "SELECT \"USER_ID\",\"EMAIL_ID\",\"PASSWORD\" FROM \"TU_IOT_PLATFORM_PROD\".\"USER_MASTER\" WHERE \"EMAIL_ID\"='john@test.com' LIMIT 1;";

                List<Map<String, Object>> toValues = new ArrayList<Map<String, Object>>();

                toValues = jdbcTemplate.queryForList(checkUser);

                if(toValues.size()>0) {
                    for (Map<String, Object> map : toValues) {
                        userDetails.setUserId((int) map.get("USER_ID"));
                        userDetails.setEmail((String)map.get("EMAIL_ID"));
                        userDetails.setPassword((String)map.get("PASSWORD"));
                    }
                }else {
                    throw new UsernameNotFoundException("User Not Found with -> username or email : " + email);
                }

                System.out.println(userDetails.toString());
                return userDetails;
            }
        } catch (NumberFormatException e) {
            userId = 0L;
            user = userRepository.findByEmail(email).orElseThrow(
                    () -> new UsernameNotFoundException("User Not Found with -> username or email : " + email));
        }
        return UserPrinciple.build(user);

    }
}

1 个答案:

答案 0 :(得分:0)

            var tokenExpiration = Startup.TokenExpiration;  //超期时长
        var data = new Dictionary<string, string>
            {
                {"as:client_id", clientId },
                {"userID",user.Id},
                {"commID","0" }
            };

        var IssueTime = DateTime.UtcNow;
        var properties = new AuthenticationProperties(data)
        {
            IssuedUtc = IssueTime,
            ExpiresUtc = IssueTime.Add(tokenExpiration),
        };
        var oAuthIdentity = _userManager.CreateIdentity(user, "JWT");
        var ticket = new AuthenticationTicket(oAuthIdentity, properties);
        var accessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
        //var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);

        //var rToken=  Startup.OAuthOptions.RefreshTokenFormat.Protect(ticket);
        var context = new AuthenticationTokenCreateContext(Request.GetOwinContext(), Startup.OAuthOptions.AccessTokenFormat, ticket);
        //await Startup.OAuthOptions.AccessTokenProvider.CreateAsync(context);
        //accessToken = context.Token;

        var refreshTkLifeTime = ;
        context.OwinContext.Set("as:clientAllowedOrigin", "*");
        context.OwinContext.Set("as:clientRefreshTokenLifeTime", refreshTkLifeTime.ToString());
        await Startup.OAuthOptions.RefreshTokenProvider.CreateAsync(context);
        var refreshToken = context.Token;

        return new JObject(
            new JProperty("access_token", accessToken),
            new JProperty("refresh_token", refreshToken),
            new JProperty("token_type", "bearer"),
            new JProperty("expires_in", tokenExpiration.TotalSeconds.ToString()),
            new JProperty(".issued", IssueTime.ToString()),
            new JProperty(".expires", IssueTime.Add(tokenExpiration).ToString())    
        );