在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java/ spring boot結合 security實現角色權限控制問題?

spring boot結合 security實現角色權限控制問題?

在springboot中集成spring security,實現不同角色的權限控制,有以下幾個問題,希望幫忙解答一下,感激不盡,很久都沒有解決。

問題1:登錄處理url報403錯誤(因為權限問題無法訪問),按照之前提過的問題,將http.csrf().disable()之后,登錄url是可以訪問了,但我不想這樣做。有什么辦法嗎?

問題2:自定義UserDetailService中的loadUserByUsername,沒有獲取到前臺的值(前臺傳的參數是account和pwd),如果改成參數改成username和pwd,就可以獲取到前臺的值。

問題3:真正的登錄驗證函數沒有被執(zhí)行到(沒有返回相應數據),只執(zhí)行了loadUserByUsername,沒有執(zhí)行@RequestMapping("login")映射的方法。

我不知道是不是我的思路有問題,是不是在spring security中,執(zhí)行了loadUserByUsername,就不會執(zhí)行自己的驗證函數了?:@RequestMapping("login"),感覺應該不是這樣。

以下是spring boot集成security的主要代碼(也是在網上參考的資料):
主要參考:http://blog.csdn.net/u0127025...

WebSecurity

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    UserDetailsService customUserService() { //注冊UserDetailsService 的bean
        return new CustomUserService();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().disable().and()       //允許嵌入iframe
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/css/**", "/js/**","/images/**", "**/favicon.ico", "/lib/**").permitAll()
                .antMatchers("/admin/**").hasRole(SysConfig.ROLE_ADMIN)
                .anyRequest().authenticated().and()
                //.rememberMe().tokenValiditySeconds(60 * 60 * 24 * 7).key("").and()
                .formLogin().loginProcessingUrl("/user/login").loginPage("/login.html").permitAll().and()
                .logout().permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserService());
    }
}

CustomUserService

@Service
public class CustomUserService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        System.out.println("loadUser " + account);
        User user = userService.getUserByAccount(account);
        if (user == null || user.isHasDel()) {
            throw new UsernameNotFoundException("user not exist or has been deleted");
        }
        List<GrantedAuthority> auths = new ArrayList<>();
        for (Role role : user.getRoles()) {
            auths.add(new SimpleGrantedAuthority(role.getName())); //不同用戶會返回不同的role.name:USER, ADMIN
        }
        return new org.springframework.security.core.userdetails.User(account, user.getPwd(), auths);
    }
}

UserController中的login

    @PostMapping("login")
    public TMessage login(String account, String pwd) {
        if (StringUtil.isEmpty(account) || StringUtil.isEmpty(pwd) || !account.contains("@"))
            return new TMessage(TMessage.CODE_FAILURE, "用戶名密碼為空或格式不正確");
        if (userService.login(account, pwd))
            return new TMessage(TMessage.CODE_SUCCESS, "登錄成功");
        else
            return new TMessage(TMessage.CODE_FAILURE, "登錄失敗,請檢查用戶名和密碼");
    }

如果前臺是這樣的格式

username: a@b,
pwd: aaabbb

customservice中才能接收到username,其他參數接受不到,我想指定參數名是account,并且進入自己的處理函數(根據用戶名和密碼)

clipboard.png

回答
編輯回答
近義詞

你可以重寫方法

2018年6月13日 06:46
編輯回答
伴謊

現在新推出了一個權限框架,叫jCasbin(https://github.com/casbin/jca...)。jCasbin采用了元模型的設計思想,支持多種經典的訪問控制方案,如ACL、RBAC、ABAC,還支持對RESTful API的控制?,F在已經支持Spring Boot、JFinal等Web框架了。需要中文文檔的話,可以看這篇文章:https://blog.csdn.net/hsluoyc...,或者在百度搜索:jCasbin

2018年3月14日 20:10
編輯回答
壞脾滊

問題一:
默認Spring Security對CSRF攻擊進行了防范,該項配置默認為開的狀態(tài),它會在頁面到服務端請求過程中通過一個token來進行請求安全校驗,如果前端使用jsp來渲染,那么需要在表單增加一個隱藏域來解決:

<!-- 開啟防止CSRF攻擊 -->
<input type="hidden" name="${_csrf.parameterName }" value="${_csrf.token}" />

如果使用thymeleaf2.1+模板或者使用了Spring MVC <form:form> 標簽,那么CsrfToken這個值會被自動加入進去

If you are using Spring MVC <form:form> tag or Thymeleaf 2.1+ and are using @EnableWebSecurity, the CsrfToken is automatically included for you (using the CsrfRequestDataValueProcessor).

如果你使用的是ajax json請求,這時候就不能使用Http Paramaters來傳入這個token,這時候 你可以通過head來提交這個token,代碼如下:

<head>
    <meta name="_csrf" content="${_csrf.token}"/>
    <!-- default header name is X-CSRF-TOKEN -->
    <meta name="_csrf_header" content="${_csrf.headerName}"/>
    <!-- ... -->
</head>

基于jquery的demo:

$(function () {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
    xhr.setRequestHeader(header, token);
});
});

問題二:
Spring Security允許我們進行自定義校驗,即實現UserDetailService接口,無論你使用任何類型的數據庫存儲或者調用第三方接口,那么你需要做的是就是將其返回結果進行轉換成Spring Security.User所需要的東西,在做轉換的時候,我們可能會想到的是使用apache commons-beanutils做數據轉換(只是幫助思考,底層不一定是用它來實現),所以在使用的時候,你想使用參數名 accout轉換成spring security的username,這個只能要我們自己手動來轉換了,因為即使Spring Security再智能,他也是按照一定的約定來進行轉換,所以你轉換失敗也是正常的...

2018年8月13日 08:54