Java Spring Security hasRole() 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30788105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:10:24  来源:igfitidea点击:

Spring Security hasRole() not working

javaspringspring-mvcspring-securitythymeleaf

提问by Xipo

I'm facing a problem when using Spring Security && Thymeleaf, specifically when trying to use the hasRoleexpression. The 'admin' user has a role 'ADMIN' but hasRole('ADMIN')resolves to false anyway I try it

我在使用 Spring Security && Thymeleaf 时遇到了问题,特别是在尝试使用hasRole表达式时。'admin' 用户有一个角色 'ADMIN' 但hasRole('ADMIN')无论如何我尝试它解析为 false

My html:

我的html:

1.<div sec:authentication="name"></div> <!-- works fine -->
2.<div sec:authentication="principal.authorities"></div> <!-- works fine -->

3.<div  sec:authorize="isAuthenticated()" >true</div> <!-- works fine -->
4.<span th:text="${#authorization.expression('isAuthenticated()')}"></span> <!-- works fine -->

5.<div th:text="${#vars.role_admin}"></div> <!--Works fine -->
6.<div  sec:authorize="${hasRole('ADMIN')}" > IS ADMIN </div> <!-- Doesnt work -->
7.<div  sec:authorize="${hasRole(#vars.role_admin)}" > IS ADMIN </div> <!-- Doesnt work -->
8.<div th:text="${#authorization.expression('hasRole(''ADMIN'')')} "></div> <!-- Doesnt work -->
9.<div th:text="${#authorization.expression('hasRole(#vars.role_admin)')}"></div> <!-- Doesnt work -->

results in:

结果是:

1.admin
2.[ADMIN]
3.true
4.true
5.ADMIN
6."prints nothing because hasRole('ADMIN') resolves to false"
7."prints nothing because hasRole(#vars.role_admin) resolves to false"
8.false
9.false

I have enabled use-expressionsin my security.xml file

我在 security.xml 文件中启用了use-expressions

<security:http auto-config="true" use-expressions="true">

And also included the SpringSecurityDialect in my config

并且还在我的配置中包含了 SpringSecurityDialect

<bean id="templateEngine"
      class="org.thymeleaf.spring4.SpringTemplateEngine">
    <property name="templateResolver" ref="templateResolver" />  
    <property name="additionalDialects">
        <set>
            <bean class="org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect" />
        </set>
    </property>      
</bean>

All the necessary dependencies in my pom.xml file

我的 pom.xml 文件中的所有必要依赖项

<!--Spring security--> 
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>4.0.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>4.0.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>4.0.1.RELEASE</version>
    </dependency>        

    <!--Thymeleaf Spring Security-->
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        <version>2.1.2.RELEASE</version>
        <scope>compile</scope>
    </dependency>

Role.java

角色.java

@Entity
@Table(name = "roles")

    public class Role implements Serializable {

        @Id
        @Enumerated(EnumType.STRING)
        private RoleType name;
        //... getters, setters
    }

RoleType

角色类型

public enum RoleType {

    ADMIN 
}

And Userhas a Set of Roles

并且User有一组Roles

Why is hasRole()not working?

为什么hasRole()不工作?

I appreciate your help, thank you

感谢您的帮助,谢谢

Workaround

解决方法

th:if="${#strings.contains(#authentication.principal.authorities,'ADMIN')}"

th:if="${#strings.contains(#authentication.principal.authorities,'ADMIN')}"

采纳答案by Dmitry Stolbov

Try use hasAuthorityinstead hasRoleinside HTML-tag.

尝试使用hasAuthority,而不是hasRole内部的HTML标签。

sec:authorize="hasAuthority('ADMIN')"

回答by Faraj Farook

Refer the offcial documentation. http://www.thymeleaf.org/doc/articles/springsecurity.html

参考官方文档。http://www.thymeleaf.org/doc/articles/springsecurity.html

<div sec:authorize="hasRole('ROLE_ADMIN')">
  This content is only shown to administrators.
</div>
<div sec:authorize="hasRole('ROLE_USER')">
  This content is only shown to users.
</div>

Can you simply try it as below without the ${... }.

你能简单地尝试一下没有${... }.

<div sec:authorize="hasRole('ADMIN')">IS ADMIN</div>

I believe you have not prefixed the roles with ROLE_. If so makesure to add the prefix as well like below

我相信您没有在角色前加上ROLE_. 如果是这样,请确保添加前缀以及如下所示

<div sec:authorize="hasRole('ROLE_ADMIN')">IS ADMIN</div>

回答by rohtakdev

I had to do something similar where i needed to verify the user role. I did below

我必须在需要验证用户角色的地方做类似的事情。我在下面做了

<div th:if="${ #authorization.expression('isAuthenticated()') and #strings.contains(#authentication.principal.authorities,'ADMIN')}">          
    <a th:href="@{/somelink}">ADMIN LINK</a>
 </div>

Hope it helps someone.

希望它可以帮助某人。

回答by sirandy

I've recently had the same problem. What you need to do is:

我最近遇到了同样的问题。你需要做的是:

  1. In your html add these statements:

    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"   xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
    
  1. 在您的 html 中添加以下语句:

    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"   xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
    

(You can change between springsecurity4 or springsecurity3 depending on what you are using).

(您可以根据使用的内容在 springsecurity4 或 springsecurity3 之间进行更改)。

  1. Be sure that you have added this resource to your libraries. I'm using gradle but you can do the same with Maven.

    compile 'org.thymeleaf.extras:thymeleaf-extras-springsecurity4:2.1.2.RELEASE'
    
  2. In your SpringWebConfiguration class or xml be sure that you are adding the dialect for thymeleaf SpringSecurity: I'm using a java class for the configuration.

    @Bean
    public SpringTemplateEngine templateEngine() {
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.setTemplateResolver(templateResolver());
    templateEngine.addDialect(new SpringSecurityDialect());
    return templateEngine;
    }
    
  1. 确保您已将此资源添加到您的库中。我正在使用 gradle 但你可以用 Maven 做同样的事情。

    compile 'org.thymeleaf.extras:thymeleaf-extras-springsecurity4:2.1.2.RELEASE'
    
  2. 在您的 SpringWebConfiguration 类或 xml 中,请确保您正在为 thymeleaf SpringSecurity 添加方言:我正在使用 java 类进行配置。

    @Bean
    public SpringTemplateEngine templateEngine() {
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.setTemplateResolver(templateResolver());
    templateEngine.addDialect(new SpringSecurityDialect());
    return templateEngine;
    }
    

But you also can define as alexsource says: Spring security and Thymeleaf doesn't work

但是你也可以像 alexsource 所说的那样定义: Spring security 和 Thymeleaf 不起作用

I hope this works for you! Greetings!

我希望这对你有用!你好!

回答by Shravan Ramamurthy

I got into the same issue, its because of spring-security4.0. Due to some reason thymeleaf-extras-springsecurity4is not compatible with spring-security4.0 and thymeleaf2.x. So i downgraded spring-securityversions to 3.2.9.RELEASEand it started working. If you still want to use spring-security 4.0, then may be you can try uplifting thymeleaf-extras-springsecurity4to 3.0.0.RELEASEand thymeleafverison to 3.0

我遇到了同样的问题,因为spring-security4.0. 由于某种原因thymeleaf-extras-springsecurity4spring-security4.0 和thymeleaf2.x. 所以我将spring-security版本降级到3.2.9.RELEASE并开始工作。如果你仍然想使用 spring-security 4.0,那么你可以尝试提升thymeleaf-extras-springsecurity4to3.0.0.RELEASEthymeleafverison3.0

Or If you are using spring boot app, then the situation becomes more trickier, then the only option left would be to either downgrade the spring-securityor upgrade the spring boot version to 1.4.x (which is still in BETA)

或者,如果您使用的是 spring boot 应用程序,那么情况会变得更加棘手,那么剩下的唯一选择就是将spring-securityspring boot 版本降级或升级到 1.4.x(仍处于 BETA 中)

In your specific scenario, making the below pom changes should make hasRole working

在您的特定场景中,进行以下 pom 更改应该会使 hasRole 工作

<!--Spring security--> 
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>3.2.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>3.2.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>3.2.9.RELEASE</version>
    </dependency>        

    <!--Thymeleaf Spring Security-->
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        <version>2.1.2.RELEASE</version>
        <scope>compile</scope>
    </dependency>

回答by Jeffrey B.

I've had the same issue upgrading from Spring Security 3.x to 4.x. Changing hasRole()to hasAuthority()did the trick for me.

我在从 Spring Security 3.x 升级到 4.x 时遇到了同样的问题。更改hasRole()hasAuthority()对我有用。

http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#el-common-built-in

http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#el-common-built-in

回答by Huy Quang

You are missing a concept:

你缺少一个概念:

  • If you use hasRole('ADMIN'), in your ADMIN Enummust be ROLE_ADMINinstead of ADMIN.
  • If you use hasAuthority('ADMIN'), your ADMIN Enummust be ADMIN.
  • 如果您使用hasRole('ADMIN'),在您的ADMIN Enum必须是ROLE_ADMIN代替ADMIN
  • 如果你使用hasAuthority('ADMIN'),你ADMIN Enum必须是ADMIN

In spring security, hasRole()is the same as hasAuthority(), but hasRole()function map with Authoritywithout ROLE_prefix.

在 spring security 中,hasRole()与 相同hasAuthority(),但hasRole()函数映射Authority没有ROLE_前缀。

You can find the accepted answer in this post: Difference between Role and GrantedAuthority in Spring Security

您可以在这篇文章中找到公认的答案:Spring Security 中 Role 和 GrantedAuthority 的区别

回答by pperez

after weeks of trial and error, this worked for me:

经过数周的反复试验,这对我有用:

Upgrading to the latest version according to https://mvnrepository.com/

根据https://mvnrepository.com/升级到最新版本

Spring Boot Starter Thymeleaf Extras Spring Security 5 Thymeleaf for Spring Boot

Spring Boot Starter Thymeleaf Extras Spring Security 5 Thymeleaf for Spring Boot

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
        <version>2.3.0.RELEASE</version>
    </dependency>

Really don′t know wich version of the dependencies work well with other versions, but for now (May 19th 2020) it worked for me.

真的不知道哪个版本的依赖项适用于其他版本,但现在(2020 年 5 月 19 日)它对我有用。

Hope it can help someone

希望它可以帮助某人