Spring引导JWT无法授权rest api

问题描述 投票:0回答:1

我正在尝试在Spring Boot 2项目上实现JWT。

我的推荐链接https://www.callicoder.com/spring-boot-spring-security-jwt-mysql-react-app-part-2/

我的Securityconfig文件是

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
        prePostEnabled=true,
        jsr250Enabled = true,
        securedEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private Environment env;

    @Autowired
    private UserSecurityService userSecurityService;


    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

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



    private BCryptPasswordEncoder passwordEncoder() {
        return SecurityUtils.passwordEncoder();
    }


    @Autowired
    private SecurityHandler securityHandler;


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
            .authorizeRequests()

        /*  antMatchers("/**").*/
            .antMatchers(PUBLIC_MATCHERS).
            permitAll().anyRequest().authenticated();

        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","/login",
                        "/api/auth/signin")
                .permitAll()
                .antMatchers("/api/auth/**")
                .permitAll()
                .antMatchers("/api/user/checkUsernameAvailability", "/api/user/checkEmailAvailability")
                .permitAll()
                .antMatchers(HttpMethod.GET, "/api/polls/**", "/api/users/**")
                .permitAll()
                .anyRequest()
                .authenticated();


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

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userSecurityService).passwordEncoder(passwordEncoder());
    }

    @Bean(BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    @Override
    public void configure(WebSecurity web) throws  Exception{
        web.ignoring()
                .antMatchers("/api/updateCardStatus","/api/login","*/uploads/***","/api/getUsersDetail","/api/getStudentDetails","/api/getAccountLoad","/api/issueDirectives","/api/changePassword","/api/cardActivation","/api/CustomerAccountCardDetails","/api/accountLoad","/api/updateConsumersProfile","/api/verifyCvv"
                        ,"/api/updatePrepaidCardStatus","/api/getStatementData");
    }

}

我的用户类

@Entity
public class User  {


    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id", nullable = false, updatable = false)
    private Long id;

    private String username;
    private String password;
    private String userType;
    private boolean enabled=true;

    @OneToOne(mappedBy = "user")
    private BankUserDetails bankUserDetails;

    @OneToOne(mappedBy = "user")
    private SctUserDetails sctUserDetails;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JsonIgnore
    private List<UserRole> userRoles = new ArrayList<>();
}

user role.Java

@Entity
@Table(name="user_role")
public class UserRole {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long userRoleId;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="user_id")
    private User user;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="role_id")
    private Role role;

}

role.Java

@Entity
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int roleId;
    private String name;

    @OneToMany(mappedBy = "role", cascade=CascadeType.ALL, fetch=FetchType.LAZY)
    private List<UserRole> userRoles = new ArrayList<>();

    public int getRoleId() {
        return roleId;
    }

    public void setRoleId(int roleId) {
        this.roleId = roleId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<UserRole> getUserRoles() {
        return userRoles;
    }

    public void setUserRoles(List<UserRole> userRoles) {
        this.userRoles = userRoles;
    }
}

user principal.Java

public class UserPrincipal implements UserDetails {
    private Long id;

    private String username;
    private String password;
    private String userType;
    private boolean enabled=true;


    @JsonIgnore
    private static List<UserRole> userRoles = new ArrayList<>();

    private Collection<? extends GrantedAuthority> authorities;

    public UserPrincipal(Long id,  String username,  String password, Collection<? extends GrantedAuthority> authorities) {
        this.id = id;
        this.username = username;
        this.password = password;
        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());*/

            List<GrantedAuthority> authorites = new ArrayList<>();
            userRoles.forEach(ur -> authorites.add(new Authority(ur.getRole().getName())));


        return new UserPrincipal(
                user.getId(),
                user.getUsername(),
                user.getPassword(),
                authorites
        );
    }


    public Long getId() {
        return id;
    }


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

现在,当我试图从邮递员那里打电话给http://localhost:5060/token/generate-token时,我得到了答复

{
    "timestamp": "2018-09-05T09:15:09.797+0000",
    "status": 401,
    "error": "Unauthorized",
    "message": "Sorry, You're not authorized to access this resource.",
    "path": "/token/generate-token"
}

现在我认为这是因为我无法获得所需的权限。

由于我的实体与示例中给出的实体不同,我猜我无法获取完全认证的用户对象。我可能错了,但有人可以帮我指出确切的问题吗?

java spring rest spring-boot jwt
1个回答
0
投票

您必须执行三个主要步骤来测试此示例。首先,您必须在角色表中插入一些角色。之后,您必须将用户注册到该应用程序。最后你可以登录。

此消息表示您未注册此用户。

这个示例有点复杂,因为一起存在一些不同的东西,你可以在这个URL中找到这个简单的例子:

http://www.jndanial.com/54

© www.soinside.com 2019 - 2024. All rights reserved.