2017-12-07 30 views
1

私は複数のロール(ROLE1、ROLE2)を持つ安全なスプリングブートアプリケーションを持っています。一方のユーザーは両方の役割を持ち、もう一方のユーザーは1つの役割しか持ちません。ログインが成功すると、ユーザーはリンク先ページに送られます。ユーザーが1つの役割しか持たない場合、要素を無効にします。ロールに基づいてHTML要素を無効/有効にするSpringboot + Thymeleaf

私はthymeleaf-extras-springsecurity3を試しましたが、成功しませんでした。これは私のコードです:(すべてのオプションを試してみました)

のpom.xml

... 
<dependency> 
      <groupId>org.thymeleaf.extras</groupId> 
      <artifactId>thymeleaf-extras-springsecurity3</artifactId> 
      <version>3.0.2.RELEASE</version> 
     </dependency> 
... 

landing.html

!${currentUser.user.hasAuthority('ROLE1')} 
!${#authorization.expression('hasRole('ROLE1')')} 
${#authentication.getPrincipal().getUser().getRoles()} 
${#authentication.getPrincipal().getRoles()} 

しかし、成功しません、私はいつも、そのオブジェクトにnullエラーが発生しますこのように

org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method getPrincipal() on null context object 

ご協力いただければ幸いです!ありがとう!

答えて

2

私はあなたがおそらく(私は春ブートはデフォルトでそれをしないと思います)もSpringSecurityDialectを設定する必要がありますsec:authorize="hasRole('ROLE_ADMIN')"

<html xmlns:th="http://www.thymeleaf.org" 
     xmlns:sec="http://www.thymeleaf.org/extras/spring-security"> 
<head>...</head> 
<body> 
    <div sec:authorize="hasRole('ROLE_ADMIN')">...</div> 

    // or use #authorization, but use escape quote 'hasRole(''ROLE_USER'')' 
    <div th:if="${#authorization.expression('hasRole(''ROLE_USER'')')}">...</div> 
</body> 

をしたいrecommended方法は、結果を達成するためにxmlns:sec="http://www.thymeleaf.org/extras/spring-security"名前空間を使用することだと思いますそれを機能させる。 Spring Security hasRole() not working

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

private IDialect securityDialect(){ 
    SpringSecurityDialect dialect = new SpringSecurityDialect(); 
    return dialect; 
} 

も同様の質問を見てみましょう

関連する問題