如何获得Spring Security中的userInformation?

时间:2018-07-08 14:37:11

标签: java spring spring-boot spring-security jwt


假设我在spring boot应用程序中有一个rest服务。
对于前端,我要登录我的应用程序,并且用户必须显示自己的信息,例如用户名,userFullName,birthdayDay等。
首先,用户必须获得令牌,然后用户必须获得带有两个差异请求的用户信息(用户名,userFullaname,birthdayDay),或者当用户获得令牌时,用户必须在一个操作中同时获得这两个信息?

例如下面的代码,您可以看到我将返回令牌。

public static void addAuthentication(HttpServletResponse res, Authentication auth) {
    try {
        String concattedRoles = "";
        for (GrantedAuthority ga : auth.getAuthorities()) {
            if (!"".equals(concattedRoles)) {
                concattedRoles += "," + ga.getAuthority();
            } else {
                concattedRoles += ga.getAuthority();
            }

        }

        String JWT = Jwts.builder().setSubject(auth.getName()).claim("roles", concattedRoles)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
                .signWith(SignatureAlgorithm.HS512, SECRET).compact();
        res.addHeader(HEADER_STRING, TOKEN_PREFIX + " " + JWT);//add header
        res.getWriter().append("{\"token\":\""+TOKEN_PREFIX + " " + JWT+"\"}");//add body
    }catch (Exception e){
        e.printStackTrace();
    }
}

如果上面的代码是我从数据库中获取的用户信息,如下面的代码,这种方法是否正常?

@Autowired
UserRepository userRepository;
User user = (User)auth.getPrincipal();
String username = user.getUsername();
UserEntity userEntity = userRepository.findByUsername(username);

res.getWriter()。append(userEntity); //关于例如。

3 个答案:

答案 0 :(得分:1)

您只需要做的就是创建自己的UserDetailsService实现,该实现将返回您自己的UserDetails对象的实现。

有关实现基于JPA的UserDetailsService的教程,请参见here

根据https://stackoverflow.com/a/20350591/6572971改编的答案

也在此线程上检查其他答案。

答案 1 :(得分:0)

如果您确实希望避免第二次请求检索用户信息,则可以将用户的生日等添加到JWT令牌中的声明中。然后,令牌本身包含您想要了解的有关用户的所有信息,而无需第二次访问数据库。

请注意,这还会增加令牌的大小,并使加密和解密花费的时间更长。

答案 2 :(得分:0)

谢谢大家。 最后,我如下解决了这个问题。
我使用org.springframework.security.core.userdetails包中的UserDetails,UserDetailsS​​ervice接口。

package com.example.notarydemo.entity;

import com.fasterxml.jackson.annotation.JsonManagedReference;

import javax.persistence.*;
import java.util.Collection;
import java.util.List;

@Entity

@NamedStoredProcedureQueries({
        @NamedStoredProcedureQuery(name = "search_user",
                procedureName = "search_user",
                resultClasses = {AppUser.class},
                parameters = {
                        @StoredProcedureParameter(mode = ParameterMode.IN, name = "id", type = Integer.class),
                        @StoredProcedureParameter(mode = ParameterMode.IN, name = "username", type = String.class),
                        @StoredProcedureParameter(mode = ParameterMode.IN, name = "enabled", type = String.class),
                        @StoredProcedureParameter(mode = ParameterMode.OUT, name = "cur", type = AppUser.class)
                })})
@Table(name = "APP_USER", schema = "MEHMAN")
public class AppUser {
    private long id;
    private String username;

    private String fulName;
    private String encrytedPassword;
    private long enabled;
    private Collection<UserRole> userRolesById;

    public AppUser(String userName, String fulName) {
        this.username = userName;
        this.fulName = fulName;
    }

    public AppUser() {
    }

    @Id
    @Column(name = "ID", nullable = false, precision = 0)
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    @Basic
    @Column(name = "USER_NAME", nullable = false, length = 36)
    public String getUsername() {
        return username;
    }

    public void setUsername(String userName) {
        this.username = userName;
    }

    @Basic
    @Column(name = "FULLNAME", nullable = false, length = 45)
    public String getFULLNAME() {
        return fulName;
    }

    public void setFULLNAME(String fullName) {
        this.fulName = fullName;
    }

    @Basic
    @Column(name = "ENCRYTED_PASSWORD", nullable = false, length = 128)
    public String getEncrytedPassword() {
        return encrytedPassword;
    }

    public void setEncrytedPassword(String encrytedPassword) {
        this.encrytedPassword = encrytedPassword;
    }

    @Basic
    @Column(name = "ENABLED", nullable = false, precision = 0)
    public long getEnabled() {
        return enabled;
    }

    public void setEnabled(long enabled) {
        this.enabled = enabled;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        AppUser appUser = (AppUser) o;

        if (id != appUser.id) return false;
        if (enabled != appUser.enabled) return false;
        if (username != null ? !username.equals(appUser.username) : appUser.username != null) return false;
        if (encrytedPassword != null ? !encrytedPassword.equals(appUser.encrytedPassword) : appUser.encrytedPassword != null)
            return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = (int) (id ^ (id >>> 32));
        result = 31 * result + (username != null ? username.hashCode() : 0);
        result = 31 * result + (encrytedPassword != null ? encrytedPassword.hashCode() : 0);
        result = 31 * result + (int) (enabled ^ (enabled >>> 32));
        return result;
    }

    @OneToMany(mappedBy = "appUserByUserId")
    @JsonManagedReference
    public Collection<UserRole> getUserRolesById() {
        return userRolesById;
    }

    public void setUserRolesById(Collection<UserRole> userRolesById) {
        this.userRolesById = userRolesById;
    }
}





package com.example.notarydemo.model;

import com.example.notarydemo.entity.AppUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;

public class MyUserPrincipal implements UserDetails {
    private AppUser user;

    public MyUserPrincipal(AppUser user) {
        System.out.println(user.getFULLNAME() + user.getUsername() + user.getEnabled());
        this.user = user;
    }

    public AppUser getUser() {
        return user;
    }

    public void setUser(AppUser user) {
        this.user = user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return null;
    }

    @Override
    public String getPassword() {
        return user.getEncrytedPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        if (user.getEnabled() == 1)
        return true;
        return false;
    }
}





package com.example.notarydemo.config;

import com.example.notarydemo.entity.AppUser;
import com.example.notarydemo.model.MyUserPrincipal;
import com.example.notarydemo.model.UserTokenInfoObject;
import com.example.notarydemo.repository.AppUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private AppUserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            AppUser user = userRepository.findByUsername(username);
            if (user == null)
                throw new UsernameNotFoundException(username);
        return new MyUserPrincipal(user);
    }
}





public static void addAuthentication(HttpServletResponse res, Authentication auth) {
        try {
            String concattedRoles = "";
            for (GrantedAuthority ga : auth.getAuthorities()) {
                if (!"".equals(concattedRoles)) {
                    concattedRoles += "," + ga.getAuthority();
                } else {
                    concattedRoles += ga.getAuthority();
                }

            }

            String JWT = Jwts.builder().setSubject(auth.getName()).claim("roles", concattedRoles)
                    .setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
                    .signWith(SignatureAlgorithm.HS512, SECRET).compact();
            res.addHeader(HEADER_STRING, TOKEN_PREFIX + " " + JWT);
           MyUserPrincipal user = (MyUserPrincipal) auth.getPrincipal();

            System.out.println(user.getUser().getFULLNAME());
            res.getWriter().append("{\"token\":\""+TOKEN_PREFIX + " " + JWT+"\"}");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

http://www.baeldung.com/spring-security-authentication-with-a-database