2017-08-16 12 views
0

私はSpringセキュリティとThymeleafでプロジェクトを進めています。私は基本的なSpring Securityの統合を持っています。学生、教授や管理者:SpringセキュリティとThymeleafを使用するロールに応じてリダイレクトするページ -

SecurityConfig.java

@Configuration 
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter{ 

    @Autowired 
    private DataSource dataSource; 

    @Autowired 
     public void configureGlobal (AuthenticationManagerBuilder auth) throws Exception 
     { 
     auth 
      .jdbcAuthentication() 
      .dataSource(dataSource); 
     } 

    protected void configure(HttpSecurity http) throws Exception { 
     http 
      .authorizeRequests() 
       .antMatchers("/login").permitAll() 
       .antMatchers("/classesTable").hasRole("ADMIN") 
       .anyRequest().authenticated() 
       .and() 
      .formLogin() 
       .loginPage("/login") 

       .and() 
      .httpBasic(); 
     } 
} 

SecurityWebApplicationInitializer.java

私のプロジェクトで
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer 
{ 
    public SecurityWebApplicationInitializer(){ 
     super(SecurityConfig.class); 
    } 

} 

私は3つの役割を持っています。 私が達成したいのは、生徒がログインしてindexUser.htmlページにリダイレクトされたときです。教授がログインすると、indexProfesor.htmlにリダイレクトされ、管理者がindexAdmin.htmlページに移動します。

私はこの

if(role.contains("ROLE_ADMIN")){ 
     //redirect from here to indexAdmin.html 

    }else if(role.contains("ROLE_USER")) { 
     //redirect to indexUser.html 
    }else 
     //redirect to indexProfesor.html 
} 

のような心の何かに持っていた。しかし、私はどのように全体のコントローラのようになります絵を持っていません。

次のようになります私のhomeContorllerがあります:

@Controller 
public class HomeController { 

    @RequestMapping(value = "/login", method = RequestMethod.GET) 
    public String loginPage(Model model) { 
     return "login"; 
    } 
} 

はまた、私はだから私は私のログインユーザーが持っている役割に精通しています私のindex.htmlに

<span sec:authorize="isAuthenticated()"> 
<span sec:authentication="name"></span> 
| Roles: <span sec:authentication="principal.authorities"></span> | 

をこのコードを追加しました。 Spring MVCのは、自動的にいくつかのHttpServletRequestを注入します

@RequestMapping(value = "/login", method = RequestMethod.GET) 
public String loginPage(Model model, HttpServletRequest request) { 
    if(request.isUserInRole("ROLE_ADMIN") { 
     // redirect to indexAdmin.html page 
    } else if(request.isUserInRole("ROLE_USER") { 
     // redirect indexUser.html page 
    } else { 
     // redirect to indexProfesor.html page 
    } 
} 

:ここ は、としてあなたのコントローラメソッドを変更することができ、また、私のlogin.htmlとのコード

<form th:action="@{/login}" method="post" class="l-form"> 
    <input type="text" name="username"/> 
    <input type="password" name="password"/> 
    <input type="hidden" th:name="${_csrf.parameterName}" 
    th:value="${_csrf.token}" /> 

    <button type="submit" class="btn">Sign in!</button> 
</form> 

答えて

1

私に適したソリューションが見つかりました。

私は、SpringConfigファイルにhttp.formLogin().defaultSuccessUrl("/success", true)を追加しました。

だから、この

protected void configure(HttpSecurity http) throws Exception { 
     http 
      .authorizeRequests() 
       .antMatchers("/login").permitAll() 
       .antMatchers("/classesTable").hasRole("ADMIN") 
       .anyRequest().authenticated() 
       .and() 
      .formLogin() 
       .loginPage("/login") 
       .defaultSuccessUrl("/success", true) 
       .and() 
      .httpBasic(); 
     } 

のように見えるそれから私はloginPageRedirect

@Controller 
public class HomeController { 

@RequestMapping(value = "/login", method = RequestMethod.GET) 
    public String loginPage(Model model) { 
     return "login"; 
    } 

    @RequestMapping("/success") 
    public void loginPageRedirect(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException, ServletException { 

     String role = authResult.getAuthorities().toString(); 

     if(role.contains("ROLE_ADMIN")){ 
     response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/indexAdmin"));        
     } 
     else if(role.contains("ROLE_USER")) { 
      response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/indexUser")); 
     } 
    } 

} 

呼ばにHomeControllerで新しいメソッドを作り、それは同じ問題を持つ人がお役に立てば幸いです。

+0

私たちの答えがあなたに役立つならば、答えをアップアップすることができます。また、あなたはより多くのことに役立つものを受け入れることができます。そして、これは他人の助けを認識する方法です。ありがとうございます – sunkuet02

+0

@ sunkuet02そのノートメイトありがとう! –

0

最初の方法

  • ですrequestパラメーターのプロパティーを使用すると、このメリットを利用できます。ここで

    @RequestMapping(value = "/login", method = RequestMethod.GET) 
    public String loginPage(Model model, Authentication authentication) { 
        if(authentication.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_ADMIN"))) { 
         // redirect to indexAdmin.html page 
        } else if(authentication.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_USER"))) { 
         // redirect indexUser.html page 
        } else { 
         // redirect to indexProfesor.html page 
        } 
    } 
    

    、春のMVCは自動的にauthenticationオブジェクトにAuthenticationプロパティを注入します:よう

別の方法

  • あなたは、コントローラのメソッドを変更することができます。

+0

私はすでに自分のユーザーの役割に精通しています。コード更新を確認してください。私は彼が持っている役割に基づいて彼を別のページにリダイレクトしようとしています。 @ sunkuet02 –

+0

@dome、私の更新された回答を参照してください – sunkuet02

+0

私はちょうど他の答えにコメントを書いています...私は "/ successLogin"とマッピングして別のコントローラを作成する必要があると思うし、 。私が "/ login"というマッピングを付けてこのように置くと、私はログインページに辿り着くことはありません。どうすればいいですか?_ –

0

あなたのコントローラメソッドでSpring MVCのがあなたのために注入し、その後HttpServletRequest#isUserInRole(String)を使用しますHttpServletRequestパラメータを公開することができます。 - > "/your/static/resource/indexAdmin.html"

  • "indexUser" - > "

    • "indexAdmin":また、あなたは以下のようにあなたのビューをマップしたと仮定し

      /your/static/resource/indexUser.html」

    • "indexProfesor" - > "/your/static/resource/indexProfesor.html"

    方法は、以下のようになり:上記スプリングドキュメントリンクで述べたよう

    @Controller 
        public class HomeController { 
    
         @RequestMapping(value = "/login", method = RequestMethod.GET) 
         public String loginPage(HttpServletRequest httpServletRequest, Model model) { 
          if(httpServletRequest.isUserInRole("ADMIN")) { 
           return "indexAdmin"; 
          } else if(httpServletRequest.isUserInRole("USER")) { 
           return "indexUser"; 
          } else { 
           return "indexProfesor"; 
          } 
         } 
        } 
    

    [..]典型的にはユーザは、この 方法に「ROLE_」プレフィックスを渡してはなりません[..]

  • +0

    ありがとうございます。私は、例えば "/ successLogin"のようにマッピングして別のコントローラを作成し、それにあなたが上で書いたロジックを置く必要があると思います。私が "/ login"というマッピングを付けてこのように置くと、私はログインページに辿り着くことはありません。あなたはそれをどうやって行うのか考えていますか? –

    +0

    また、私のlogin.htmlで編集した質問 –

    関連する問題