1package com.mkyong.config;
2
3import javax.sql.DataSource;
4import org.springframework.beans.factory.annotation.Autowired;
5import org.springframework.context.annotation.Configuration;
6import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
7import org.springframework.security.config.annotation.web.builders.HttpSecurity;
8import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
9import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
10
11@Configuration
12@EnableWebSecurity
13public class SecurityConfig extends WebSecurityConfigurerAdapter {
14
15 @Autowired
16 DataSource dataSource;
17
18 @Autowired
19 public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
20
21 auth.jdbcAuthentication().dataSource(dataSource)
22 .usersByUsernameQuery(
23 "select username,password, enabled from users where username=?")
24 .authoritiesByUsernameQuery(
25 "select username, role from user_roles where username=?");
26 }
27
28 @Override
29 protected void configure(HttpSecurity http) throws Exception {
30
31 http.authorizeRequests()
32 .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
33 .and()
34 .formLogin().loginPage("/login").failureUrl("/login?error")
35 .usernameParameter("username").passwordParameter("password")
36 .and()
37 .logout().logoutSuccessUrl("/login?logout")
38 .and()
39 .exceptionHandling().accessDeniedPage("/403")
40 .and()
41 .csrf();
42 }
43}
44Copy