Я не могу сгенерировать токен доступа? - PullRequest
0 голосов
/ 07 января 2019

Я применяю весеннюю безопасность в своем проекте ... и У меня проблема с генерацией токенов доступа? Как я могу сгенерировать токен доступа ??

UserPrincipal

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);
    }
}

UserController

@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";
        }

    }

SecurityConfig

public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    CustomUserDetailsService customUserDetailsService;

    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter() {
        return new JwtAuthenticationFilter();
    }


    @Override
    public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder
                .userDetailsService(customUserDetailsService)
                .passwordEncoder(passwordEncoder());

    }

    @Bean(BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
        DefaultHttpFirewall firewall = new DefaultHttpFirewall();
        firewall.setAllowUrlEncodedSlash(true);
        return firewall;
    }
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.httpFirewall(allowUrlEncodedSlashHttpFirewall());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                .csrf()
                .disable()
                .exceptionHandling()
                .authenticationEntryPoint(unauthorizedHandler)
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/",
                        "/favicon.ico",
                        "/**/*.png",
                        "/**/*.gif",
                        "/**/*.svg",
                        "/**/*.jpg",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js")
                .permitAll()
                .antMatchers("/api/auth/**")
                .permitAll()
                .antMatchers("/api/user/checkUsernameAvailability", "/api/user/checkEmailAvailability")
                .permitAll()
                .antMatchers(HttpMethod.GET, "/api/polls/**", "/api/user/**")
                .permitAll()
                .anyRequest()
                .authenticated();

        // Add our custom JWT security filter
        http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

    }
}

Я пытался в почтальоне, но есть ошибка 401 несанкционированного показано .. я не знаю, что за мисс часть, которую я не добавил ?? Может ли кто-нибудь предложить мне, что мне делать ?? Заранее спасибо!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...