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

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_.

主站蜘蛛池模板: 溧阳市| 金山区| 建水县| 康定县| 洪湖市| 尤溪县| 抚顺县| 青龙| 定结县| 十堰市| 马尔康县| 雅江县| 白城市| 廊坊市| 怀化市| 潍坊市| 松桃| 三门峡市| 广河县| 高青县| 资阳市| 视频| 铅山县| 清镇市| 文安县| 淮安市| 齐齐哈尔市| 伊宁县| 常州市| 衢州市| 武穴市| 莎车县| 太原市| 和平区| 徐水县| 三门县| 淮滨县| 合山市| 牟定县| 治县。| 红安县|