官术网_书友最值得收藏!

Step 1—Spring Security configuration setup

We will now create the all-important Spring Security configuration class and make sure that the default filter chain for Spring Security is set up to secure all the resources:

@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select username, password, enabled"
+ " from users where username = ?")
.authoritiesByUsernameQuery("select username, authority "
+ "from authorities where username = ?")
.passwordEncoder(new BCryptPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().hasAnyRole("ADMIN", "USER")
.and()
.httpBasic(); // Use Basic authentication
}
}

In Spring Security configuration, the first thing that we do is tell Spring Security that you will have to authenticate the user against a database by using a defined user query and checking the user's authority using the defined authority query.

We then set up the authentication mechanism to retrieve the user's credentials. Here we are using basic authentication as the mechanism to capture user credentials. Please note that the role names being used to check doesn't have the prefix ROLE_.

主站蜘蛛池模板: 福州市| 黄大仙区| 济宁市| 宾川县| 新绛县| 秀山| 石泉县| 磴口县| 沙洋县| 榆中县| 乳源| 馆陶县| 霍林郭勒市| 巧家县| 宣汉县| 海原县| 孝昌县| 白山市| 交城县| 伊金霍洛旗| 临海市| 阿图什市| 祁阳县| 汝城县| 荆州市| 肥城市| 淮北市| 额尔古纳市| 泉州市| 海林市| 伊吾县| 泗阳县| 育儿| 平塘县| 休宁县| 青海省| 祁东县| 石首市| 沙雅县| 泰州市| 天峻县|