亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Spring security:使用數據庫中的角色登錄

Spring security:使用數據庫中的角色登錄

Helenr 2023-09-27 10:15:22
我在 db: 中有 3 個表USER(login,password),ROLE(role_name)并且USER_ROLE_LINK (user_id, role_id)我想為具有特定角色的用戶授予對特定頁面的訪問權限。我在這個類中配置了安全性:@Configuration@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter{    @Autowired    private DataSource dataSource;    @Override    protected void configure(HttpSecurity http) throws Exception     {        http            .csrf()            .disable()            .authorizeRequests()            .antMatchers("/", "/home").permitAll()            .anyRequest()            .authenticated()            .and()            .formLogin()            .loginPage("/login")            .permitAll()            .and()            .logout()            .permitAll();    }    @Override    protected void configure(AuthenticationManagerBuilder auth) throws Exception    {        auth.jdbcAuthentication()            .dataSource(dataSource)            .passwordEncoder(NoOpPasswordEncoder.getInstance())            .usersByUsernameQuery("select login, password, active from USER where login=?")            .authoritiesByUsernameQuery("select ur.user_id, ur.role_id from USER u inner join USER_ROLE_LINK ur on u.id = ur.user_id where u.login=?");    }}它工作正常,只有那些至少擁有一個角色的用戶才能訪問該應用程序?,F在我想為具有特定角色的用戶授予特定頁面的訪問權限,該怎么做?我已經嘗試過這個:antMatchers("/mypage").hasRole("MODERATOR")但它會拋出403 error. 我應該如何告訴從表的列Spring中查找用戶的角色?ROLErole_name
查看完整描述

1 回答

?
回首憶惘然

TA貢獻1847條經驗 獲得超11個贊

效果好嗎?

不,方法參數中的查詢字符串錯誤.authoritiesByUsernameQuery。

查詢返回類型即結果集應該是用戶名和角色

SELECT username, role

如果連接查詢結果結果集列名稱如下所示:

https://img1.sycdn.imooc.com//651390780001680e02050037.jpg

您應該修改為如下所示:

https://img1.sycdn.imooc.com//651390840001dcdd01830038.jpg

通過使用別名SELECT ud.username AS username, rm.name AS role

我試過這個: antMatchers("/mypage").hasRole("MODERATOR") 但它拋出 403 錯誤

它不會工作,因為您的授權部分不正確。

我應該如何告訴Spring從ROLE表的role_name列中查找用戶的角色?

需要完整的認證和授權配置。請參閱下面的相同內容。

我將舉一個可行的例子:

考慮您的要求具有類似的三個表userdetailsrolemaster、 和 ,user_role_mapping如下所示。

https://img1.sycdn.imooc.com//6513909000011aff06530372.jpg

那么你的配置將是


@Configuration

@EnableWebSecurity

public class SpringSecurityConfig extends WebSecurityConfigurerAdapter 

{


    @Autowired

    DataSource dataSource;


    @Autowired

    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception

    {

    //If you want to store plain password you can use NoOpPasswordEncoder

    auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(passwordEncoder())

                .usersByUsernameQuery("select username, password, enabled from userdetails where userName=?")

                .authoritiesByUsernameQuery(

                        "SELECT ud.username AS username, rm.name AS role FROM user_role_mapping map " + 

                        "INNER JOIN userdetails ud ON map.userId = ud.id " + 

                        "INNER JOIN rolemaster rm ON  map.roleId = rm.id  where userName = ?");

    }


    @Override

    protected void configure(final HttpSecurity http) throws Exception

    {

        http

        .authorizeRequests()

            .antMatchers("/resources/**", "/", "/login", "/api/**").permitAll()

            .antMatchers("/config/**", "/app/admin/**")

                .hasRole("ADMIN")

            .antMatchers("/app/user/**")

            .hasAnyRole("ADMIN", "USER")

        .and().exceptionHandling().accessDeniedPage("/403")

        .and().formLogin()

            .loginPage("/login")

            .usernameParameter("userName").passwordParameter("password") 

            .defaultSuccessUrl("/app/user/dashboard")

            .failureUrl("/login?error=true")

        .and().logout()

            .logoutSuccessHandler(new CustomLogoutSuccessHandler())

            .invalidateHttpSession(true)

        .and()

            .csrf()

                .disable();


        http.sessionManagement().maximumSessions(1).expiredUrl("/login?expired=true");

    }


    @Bean

    public PasswordEncoder passwordEncoder() 

    {

        return new BCryptPasswordEncoder();

    }


}

授權部分

繞過對存儲在 resources 文件夾中的 javascript 和 css 等資源的授權。


.antMatchers("/resources/**", "/", "/login", "/api/**").permitAll()

對于管理員網址


.antMatchers("/config/**", "/app/admin/**").hasRole("ADMIN")

對于可以被多個角色訪問的url


.antMatchers("/app/user/**").hasAnyRole("ADMIN", "USER")

以及.formLogin()配置:


.usernameParameter("userName").passwordParameter("password") 

// Use above line of code if your login form param names are different 

// than defaults -> "username" "password"

.defaultSuccessUrl("/app/user/dashboard")

// If defaultSuccessUrl not configured then after login success redirects to "/"

異常處理部分


.exceptionHandling().accessDeniedPage("/403")

//If you want custom denied screen to be displayed.


查看完整回答
反對 回復 2023-09-27
  • 1 回答
  • 0 關注
  • 128 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號