Wednesday, July 26, 2017

Spring User Authentication & Authorization

-->
import.sql file will ensure that data will be loaded into the database when we boot our application

-->
dependencies {
   compile 'org.springframework.boot:spring-boot-starter-thymeleaf'    compile 'org.springframework:spring-orm:4.2.4.RELEASE'    compile 'org.springframework.data:spring-data-jpa:1.9.2.RELEASE'    compile 'org.hibernate:hibernate-core:5.0.6.Final'    compile 'org.hibernate:hibernate-entitymanager:5.0.6.Final'   compile 'org.apache.tomcat:tomcat-dbcp:8.0.30'   compile 'org.springframework.boot:spring-boot-starter-security'   compile 'org.thymeleaf.extras:thymeleaf-extras-springsecurity4:2.1.2.RELEASE'
   runtime 'com.h2database:h2'    runtime 'javax.transaction:jta:1.1'    runtime 'org.aspectj:aspectjweaver:1.8.7'
   testCompile 'org.springframework.boot:spring-boot-starter-test'}

-->Authentication
Verifying that a user is who she or he is claiming to be.
User implements UserDetails

-->Authorization
Verifying that an authenticated user has permission to perform the requested operation.
Verifying that if he is allowed to access a requested resource or perform a requested action.

-->
@Overridepublic Collection<? extends GrantedAuthority> getAuthorities() {
    List<GrantedAuthority> authorities = new ArrayList<>();    authorities.add(new SimpleGrantedAuthority(role.getName()));    return authorities;}

-->
role-id是map到role的entry name
@OneToOne@JoinColumn(name = "role_id")
private Role role;

-->Spring Data JPA
So all we have to do here is extend CrudRepository
Auto generate the method
@Repositorypublic interface UserDao extends CrudRepository<User,Long> {
    User findByUsername(String username);}

-->SecutiryConfig
@EnableWebSecurity
SecutiryConfig extends WebSecurityConfigurerAdapter

Spring Security Filter Chain

This chain allows us to filter certain requests so that a user doesn't have to be authenticated...



No comments:

Post a Comment