Employee.java
===========
package com.mycompany.myapp.entity; import javax.persistence.*; import java.util.*; @Entity @Table(name = "employee") public class Employee { private long id; private String username; private String password; @Column(name = "enabled", columnDefinition = "boolean default true",
nullable = false) private Boolean enabled = true; @Id @GeneratedValue @Column(name = "id") public long getId() { return id; } public void setId(long id) { this.id = id; }
//...
//other getters, setters
}
EmployeeRoles.java:============
package com.mycompany.myapp.entity;
import javax.persistence.*; @Entity @Table(name = "employee_roles") public class EmployeeRoles{ private int id; private String employeeCode; private String role; @Id @GeneratedValue @Column(name = "id") public int getId() { return id; } public void setId(int id) { this.id = id; } //other getters, setters
}
Initial Roles:
src/main/resources/import.sql:
====================================
insert into employee_roles(employee_code,role) values('SOME_EMPLOYEE_CODE','ROLE_USER');
Spring Security config:
WebSecurityConfig.java:
===================
package com.mycompany.myapp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication
.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders
.HttpSecurity; import org.springframework.security.config.annotation.web.configuration
.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration
.EnableWebSecurity; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation
.ResourceHandlerRegistry; import javax.sql.*; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/webjars/**","/webjars/","/img/**",
"/styles/**","/js/**","/api/1.0/get**", "/about.html")
.permitAll().anyRequest().authenticated()
.and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } @Autowired DataSource dataSource; @Autowired public void configAuthentication(AuthenticationManagerBuilder auth)
throws Exception { auth.jdbcAuthentication().dataSource(dataSource) .usersByUsernameQuery( "select username,password, enabled
from employee where username=?") .authoritiesByUsernameQuery( "select employee_code, role
from employee_roles where employee_code=?"); } }
No comments:
Post a Comment