2015-01-31 16 views
0

我的數據庫中有兩個表格。用戶和user_role。Spring,@RolesAllowed和數據庫來保護頁面

CREATE TABLE `user` (
    `username` varchar(50) NOT NULL, 
    `password` varchar(255) NOT NULL, 
    `enable` tinyint(4) NOT NULL DEFAULT '1', 
    PRIMARY KEY (`username`), 
    UNIQUE KEY `unique_username` (`username`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 

CREATE TABLE `user_roles` (
    `user_role_id` int(11) NOT NULL AUTO_INCREMENT, 
    `username` varchar(45) NOT NULL, 
    `ROLE` varchar(45) NOT NULL, 
    PRIMARY KEY (`user_role_id`), 
    UNIQUE KEY `uni_username_role` (`ROLE`,`username`), 
    KEY `fk_username_idx` (`username`), 
    CONSTRAINT `fk_username` FOREIGN KEY (`username`) REFERENCES `user` (`username`) 
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1 

在user_roles「角色」顯示角色,其用戶{ROLE_USER,ROLE_ADMIN}

我想使用@RolesAllowed拒絕用戶訪問某些網頁(和授予管理員訪問權限) ,但我不知道如何從數據庫獲取user_role並將其發送給RolesAllowed。

在控制器中獲取user_role不是問題,但我認爲在每個函數中檢查用戶角色並不是一個好主意。

或者,也許有比使用@RolesAllowed更好的解決方案?

對不起,這是一個愚蠢的問題,它是5個小時,因爲我第一次看到Spring。

回答

2

你沒有給你正在構建的應用程序的體系結構提供太多的細節,但作爲初學者,我可以給你一些我正在構建的應用程序的示例。我正在使用Spring Boot,JPA,Spring Data和Spring Security。我有一個類似的要求,並像這樣解決:

我已經實現了UserDetailsS​​ervice接口。它是用來檢索有關試圖登錄的用戶信息,由於我使用JPA和Spring數據服務和模型類看起來像這樣(的getter,setter和大多數領域爲簡潔起見刪除):

@Entity 
// in your case this would map to the User table 
public class Profile implements UserDetails { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Integer id; 

    // you should probably use bean validation/jpa to assure uniqueness etc. 
    private String name; 
    ... 

    @ElementCollection(fetch = FetchType.EAGER) 
    private Set<Role> roles = ImmutableSet.<Role> of(new Role("USER")); 
    ... 
} 

@Embeddable 
// in your case this would map to the user_role table 
public class Role implements GrantedAuthority { 

    public final static Role USER = new Role("USER"); 
    public final static Role ADMIN = new Role("ADMIN"); 

    private String authority; 

    ... 

} 

@Transactional 
@Service 
public class ProfileService implements UserDetailsService { 

    private final ProfileRepository profileRepository; 

    @Autowired 
    public ProfileService(ProfileRepository profileRepository){ 
      this.profileRepository = profileRepository; 
    } 

    public Profile loadUserByUsername(String username) throws UsernameNotFoundException { 
     Profile profile = profileRepository.findByUsername(username); 

     // this is the only way to authenticate 
     if (profile == null) { 
      throw new UsernameNotFoundException("security.userNotFound"); 
     } 

     return profile; 
    } 

// you may want to add profile creation etc. 
... 
} 

一旦我設置好了,我必須配置Spring Security來使用這個服務。我主要使用Java Config,所以配置看起來像。

@Configuration 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 
    @Autowired 
    private ProfileService profileService; 

    @Bean 
    public PasswordEncoder passwordEncoder() { 
     return new BCryptPasswordEncoder(); 
    } 

    @Override 
    protected void configure(AuthenticationManagerBuilder auth) 
     throws Exception { 
     auth.userDetailsService(profileService).passwordEncoder(passwordEncoder()); 
    } 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.formLogin() 
       .loginPage("/login") 
       .permitAll() 
       .and() 
       .authorizeRequests() 
       .antMatchers(HttpMethod.POST, "/**") 
       .authenticated() 
       ... 
       // you may want to put more config here 
     } 
}