Oauth2从令牌获取用户名

时间:2018-07-22 08:14:47

标签: spring rest spring-boot oauth-2.0 spring-security-oauth2

我已经实现了Ouath2作为我的Spring boot rest控制器的安全性。 在调用我的任何资源之前,oauth2会为用户表中的用户验证令牌。我的问题是如何避免用户1令牌位于请求中且请求正文中包含用于用户2修改的数据的情况?我需要进行检查,以便User1及其令牌应该只能为自己修改数据。如果user1的脚趾在请求正文中有user2数据,则应抛出403。

我在想是否可以从服务层的令牌中获取用户名来执行此检查?任何帮助表示赞赏

2 个答案:

答案 0 :(得分:0)

您可以通过创建自定义验证来实现。

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {OwnUserValidator.class})
public @interface OwnUser {
String message() default Messages.INVALID_WALLET;

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};
}

//

import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class OwnUserValidator implements ConstraintValidator<OwnUser, String> {

@Override
public void initialize(OwnUser constraintAnnotation) {

}

@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    String tokenName = THREAD_LOCAL_TOKEN.get();
    if(tokenName.equalsIgnoreCase(value)){
    return true;
    }
    return false;
}
}

然后在请求正文中的用户字段之前使用此 @OwnUser 注释

public class Request implements Serializable{

private static final long serialVersionUID = 1L; 

@OwnUser
private String user;
}

当请求调用doFilterInternal方法时,您将令牌保存在threadLocal中:

public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

public static ThreadLocal<String> THREAD_LOCAL_TOKEN = new ThreadLocal<>();

@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

    //get token from httpServlet request.
    THREAD_LOCAL_TOKEN.set(nameFromtoken);
    //ur neccessary code
    filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}

答案 1 :(得分:0)

您正在使用Spring Security进行身份验证。

您可以从SecurityContext获取用户详细信息

Authentication authentication = SecurityContextHolder.getContext()
    .getAuthentication();

UserDetails userDetail = authentication.getPrincipal();
userDetail.getUsername();

或在Rest Controller中

@RequestMapping(value = "/username", method = RequestMethod.GET)
public String currentUserName(Principal principal) {
    return principal.getName();
}

@RequestMapping(value = "/username", method = RequestMethod.GET)
public String currentUserName(HttpServletRequest request) {
    Principal principal = request.getUserPrincipal();

    return principal.getName();
}