如何在spring boot中获取用户对象

时间:2017-09-07 14:30:07

标签: spring spring-boot spring-security spring-data-jpa

如何获取当前用户对象以将jwt令牌存储到数据库中 当我尝试使用此User user=(User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

时,我的代码 java.lang.ClassCastException: com.owo.entity.JwtUser cannot be cast to com.owo.entity.User下方

怎么办呢?

@RestController

public class AuthenticationRestController {

private final static String THIS_CLASS = AuthenticationRestController.class.getName();

@Value("${jwt.header}")
private String tokenHeader;

@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private JwtTokenUtil jwtTokenUtil;

@Autowired
private UserDetailsService userDetailsService;

@Autowired
IUserService userService;

@Autowired
private UserRepository userRepository;


@RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest, Device device) throws AuthenticationException {

    Log.info(THIS_CLASS, "Credentials are " + authenticationRequest.getUsername() + ":" + authenticationRequest.getPassword());
    // Perform the security
    final Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(
                    authenticationRequest.getUsername(),
                    authenticationRequest.getPassword()
            )
    );

    Log.info(THIS_CLASS, "AuthenticationManager Done");

    SecurityContextHolder.getContext().setAuthentication(authentication);

    Log.info(THIS_CLASS, "SecurityContextHolder Done");
    // Reload password post-security so we can generate token
    final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
    final String token = jwtTokenUtil.generateToken(userDetails, device);

    Log.info(THIS_CLASS, "Return the token");

   //here the i want to store the jwt token into database
    User user=(User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    Date expirationDate=jwtTokenUtil.getExpirationDateFromToken(token);
    Date createdDate=jwtTokenUtil.getIssuedAtDateFromToken(token);
    userService.storeToken(user, token,expirationDate,createdDate);
    System.out.println("user is:"+user);
    System.out.println("token is"+token);
    System.out.println(expirationDate);
    System.out.println(createdDate);

    Log.info(THIS_CLASS, "Store the token,expirationDate,createdDate into Database");

    // Return the token
    return ResponseEntity.ok(new JwtAuthenticationResponse(token));
}
  

公共类JwtUser实现了UserDetails {

private final Long id;
private final String username;

private final String password;
private final String email;
private final Collection<? extends GrantedAuthority> authorities;
private final boolean enabled;
private final Date lastPasswordResetDate;

public JwtUser(
      Long id,
      String username,
    //  String firstname,
     // String lastname,
      String email,
      String password, Collection<? extends GrantedAuthority> authorities,
      boolean enabled,
      Date lastPasswordResetDate
) {
    this.id = id;
    this.username = username;
  //  this.firstname = firstname;
   // this.lastname = lastname;
    this.email = email;
    this.password = password;
    this.authorities = authorities;
    this.enabled = enabled;
    this.lastPasswordResetDate = lastPasswordResetDate;
}

// setter and getters

@Entity
@Table(name="USER")
public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="USERID")
    private Long userid;

    @Column(name="USERNAME")
    @NotNull
    private String username;

    @Column(name="USEREMAIL",unique=true)
    private String email;

    @Column(name="USERPHONE",unique=true)
    private Long phone;

    @Column(name="GOOGLE_LOGIN")
    @NotNull
    private boolean google_login;

    @Column(name="GOOGLE_TOKEN")
    @Type(type="text")
    private String google_token;

    @Column(name="FACEBOOK_LOGIN")
    @NotNull
    private boolean facebook_login;

    @Column(name="FACEBOOK_TOKEN")
    @Type(type="text")
    private String facebook_token;


    @Column(name="AADHAR_NUMBER",unique=true)
    private Long aadhar_number;

    @Column(name="USERPASSWORD")
    private String password;

    @Column(name="OTP")
    private int OTP;

    @Column(name="ACTIVATION_FLAG")
    @NotNull
    private boolean activation_flag;

    @Column(name="LOGIN_STATUS")
    @NotNull
    private boolean login_status;

    @Column(name="CREATED_AT")
    private Date created_at;

    @Column(name="UPDATED_AT")
    private Date updated_at;

    @Column(name="ENABLE_FLAG")
    @NotNull
    private boolean enable_flag;

    @Column(name="JWT_TOKEN")
    @Type(type="text")
    private String JWT_token;

    @Column(name="TOKEN_CREATED_AT")
    private Date token_created_at;

    @Column(name="TOKEN_UPDATED_AT")
    private Date token_updated_at;

    @Column(name="TOKEN_EXPIRE_AT")
    private Date token_expire_at;

    @Column(name="DEVICE_ID")
    private Long registration_device;

    @OneToMany(cascade=CascadeType.ALL)
    @JoinColumn(name="USERID")
    private Set<Audit> audit;

    @ManyToOne
    @JoinColumn(name="ADDRESSID")
    private Address address;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name = "USER_AUTHORITY",
            joinColumns = {@JoinColumn(name = "USER_ID", referencedColumnName = "USERID")},
            inverseJoinColumns = {@JoinColumn(name = "AUTHORITY_ID", referencedColumnName = "ID")})
    private List<Authority> authorities;

    private Date lastPasswordResetDate;

public final class JwtUserFactory {

private JwtUserFactory() {
}

public static JwtUser create(User user) {
    return new JwtUser(
            user.getUserid(),
            user.getUsername(),
          //  user.get,
           // user.getLastname(),
            user.getEmail(),
            user.getPassword(),
            mapToGrantedAuthorities(user.getAuthorities()),
            user.isEnable_flag(),
            user.getLastPasswordResetDate()
    );
}

private static List<GrantedAuthority> mapToGrantedAuthorities(List<Authority> authorities) {
    return authorities.stream()
            .map(authority -> new SimpleGrantedAuthority(authority.getName().name()))
            .collect(Collectors.toList());
}

}

如果还有其他方式请告诉mi .. 感谢。

1 个答案:

答案 0 :(得分:0)

您正在向用户投射,但在安全情况下,您拥有JWTUser。 只需更改演员表并从JWTUser中提取您需要的任何信息。

JWTUser user =(JWTUser)SecurityContextHolder.getContext()。getAuthentication()。getPrincipal()