我无法生成访问令牌?

时间:2019-01-07 11:02:20

标签: spring-boot authentication spring-security

我正在项目中应用春季安全性...并且 我的访问令牌生成有问题吗? 如何生成访问令牌?

UserPrincipal

Console.ForegroundColor = (ConsoleColor)10; 

UserController

public class UserPrincipal  implements UserDetails {

    private Long id;
    private String username;
    private String emailAddress;
    private String password;
    private String phoneNumber;
    private String age;
    private String bio;
    private String sex;
    private String occupation;
    private String partySupport;
    private Date joiningDate;
    private String status;
    private Address address;

    private Collection<? extends GrantedAuthority> authorities;

    public UserPrincipal(Long id, String username, String emailAddress, String password, String phoneNumber, String age, String bio, String sex, String occupation, String partySupport, Date joiningDate, String status, Address address, Collection<? extends GrantedAuthority> authorities) {
        this.id = id;
        this.username = username;
        this.emailAddress = emailAddress;
        this.password = password;
        this.phoneNumber = phoneNumber;
        this.age = age;
        this.bio = bio;
        this.sex = sex;
        this.occupation = occupation;
        this.partySupport = partySupport;
        this.joiningDate = joiningDate;
        this.status = status;
        this.address = address;
        this.authorities = authorities;
    }

    public static UserPrincipal create(User user)
    {
        List<GrantedAuthority> authorities = user.getRoles().stream().map(role ->
                new SimpleGrantedAuthority(role.getName().name())
        ).collect(Collectors.toList());

        return new UserPrincipal(
                user.getId(),
                user.getUsername(),
                user.getEmailAddress(),
                user.getPassword(),
                user.getPhoneNumber(),
                user.getAge(),
                user.getBio(),
                user.getSex(),
                user.getOccupation(),
                user.getPartySupport(),
                user.getJoiningDate(),
                user.getStatus(),
                user.getAddress(),
                authorities
        );
    }

    public Long getId() {
        return id;
    }

    public String getEmailAddress() {
        return emailAddress;
     }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public String getAge() {
        return age;
    }

    public String getBio() {
        return bio;
    }

    public String getSex() {
        return sex;
    }

    public String getOccupation() {
        return occupation;
    }

    public String getPartySupport() {
        return partySupport;
    }

    public Date getJoiningDate() {
        return joiningDate;
    }

    public String getStatus() {
        return status;
    }

    public Address getAddress() {
        return address;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public String getPassword() {
        return password;
    }

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

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

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

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

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        UserPrincipal that = (UserPrincipal) o;
        return Objects.equals(id, that.id);
    }

    @Override
    public int hashCode() {

        return Objects.hash(id);
    }
}

SecurityConfig

@RestController
@RequestMapping("/api")
@CrossOrigin(value = "http://localhost:4200", allowedHeaders = "*")
@Configuration
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PollRepository pollRepository;

    @Autowired
    private VoteRepository voteRepository;

    @Autowired
    private PollService pollService;


    private Object model;

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);


    @GetMapping("/user/all")
    @PreAuthorize("hasRole('ADMIN')")
    public List<User> getUsers() {
        return userService.getUsers();
    }

    @GetMapping("/user/getCount")
    @PreAuthorize("hasRole('ADMIN')")
    public HashMap<String, String> getCount() {
        int totalUsers = getUsers().size();
        int activeUsers = userService.getCountByActive();
        int inactiveUsers = userService.getCountByInactive();
        HashMap<String, String> userStatus = new HashMap<>();
        userStatus.put("Total",String.valueOf(totalUsers));
        userStatus.put("Active", String.valueOf(activeUsers));
        userStatus.put("Inactive",String.valueOf(inactiveUsers));
        System.out.println(userStatus);
    //   System.out.println("Inactive Users" + inactiveUsers);
        return userStatus;
    }
@GetMapping("/user/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Optional<User> getUser(@PathVariable Long id) {
        return userService.getUser(id);
    }

    @DeleteMapping("/user/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public boolean deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return true;
    }

    @PutMapping("/user")
    @PreAuthorize("hasRole('ADMIN')")
    public User updateUser(@RequestBody User user) {
        return userService.updateUser(user);
    }

    @PostMapping("/user")
    public String createUser(@RequestBody User user) {
        System.out.print("Email Address :" + user.getEmailAddress());
        User user1 = userService.createUser(user);
        if (user1 != null) {
            return "success";
        } else {
            return "failed";
        }

    }
我在邮递员中尝试过,但显示错误401未经授权。 我不知道我未添加的错过部分是什么?? 谁能建议我该怎么办? 预先感谢!

0 个答案:

没有答案