JavaSpring安全性hasanyauthority不起作用

vom3gejh  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(425)

我有一个SpringRESTful应用程序,后端是Spring2.4.3,前端是angular,当我试图限制对单个页面的访问时,我得到了401代码。我尝试了hasrole()和hasauthority()的所有变体,但没有任何帮助。我做错了什么?
securityconfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/", "/login", "/registration").permitAll()
            .antMatchers("/profile","/profile/*").hasAnyAuthority("USER","ADMIN","INTERVIEWER")
            .antMatchers("/getAllUsers").permitAll()
            .anyRequest().authenticated();
    http
            .csrf().disable()
            .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint())
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            /*.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class)*/
            .cors();
}

role.java

@XmlType
@XmlEnum
public enum Role implements GrantedAuthority {
    ADMIN,
    USER,
    INTERVIEWER;

    @Override
    public String getAuthority() {
        return this.name();
    }
}

结果:

出了点问题:(

jv2fixgn

jv2fixgn1#

根据您提供的代码,该行 .addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class) 被注解掉了。我无法说明当您取消注解该行时会发生什么(因为它是一个自定义筛选器),但如果没有该行,您将无法进行身份验证。这将导致您的入口点(您的示例中未提供)被调用,并且似乎正在返回您的401状态代码。
您可以通过注解以下行来测试这一点:

.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint())
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()

及加入 .formLogin().and() 相反表单登录将提供默认身份验证入口点、默认身份验证过滤器和(如果使用spring boot)默认用户详细信息服务,并将随机生成的密码打印到控制台,您可以使用该密码测试登录。有关这方面的更多信息,请参阅文档。
关于使用hello world(开箱即用)配置进行测试的注意事项:这是一种非常有用的技术 formLogin() 用于测试授权规则(例如。 .antMatchers("/profile","/profile/*").hasAnyAuthority("USER","ADMIN","INTERVIEWER") )Spring的安全。它允许您消除身份验证机制的问题。一旦您确信您的授权规则正常工作,就可以继续配置您自己的身份验证方案。如果可能,寻求利用spring security提供的现有方案,并且仅在无法使用现成方案时创建自定义过滤器。您可以在文档中阅读关于jwt身份验证的内容。

相关问题