限制普通用户和管理员的页面访问

时间:2019-12-02 12:39:07

标签: java spring authentication spring-security

我目前正在开发一种应用程序,用于管理大学的学生,课程,教授...。我已经使用Jpa通过Spring Security实现了身份验证。用户有2种类型:管理员和教授。管理员应该有权访问所有具有以下模式的页面:"/management/student*" , "/management/professor/*" , "/management/course*",而教授只能访问URL "/management/rooms"(因为他应该能够预定一个房间来做他的演讲)。 我尝试使用hasRole("ADMIN")方法,但是不知道如何将授权添加到特定实体。 教授课扩展了以下用户课:


@Entity
@Table(name = "user")
@Data
public class User implements Serializable, UserDetails {

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

    private String username;

    private String password;

    @Enumerated(EnumType.STRING)
    @ElementCollection(fetch = FetchType.EAGER)
    private List<Role> roles;

    @Override
    public List<GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        roles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role.toString())));

        return authorities;
    }

    @Override
    public boolean isAccountNonExpired() {

        return false;
    }

    @Override
    public boolean isAccountNonLocked() {

        return false;
    }

    @Override
    public boolean isCredentialsNonExpired() {

        return false;
    }

    @Override
    public boolean isEnabled() {

        return false;
    }

    public void grantAuthority(Role authority) {
        if (roles == null) {
            roles = new ArrayList<>();
        }
        roles.add(authority);
    }
}

教授班级:


@Entity
@Table(name = "Professor")
@Data
public class Professor extends User implements Serializable{

//fields like name email etc ...

}

UserRepository界面:

public interface UserRepository {
        @Query(" select u from User u " +
                " where u.username = ?1")
        Optional<User> findUserWithName(String username);

}

这是我的SecurityConfig类,我要在其中定义页面限制:


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserService userDetailsService;

    @Autowired
    private AccessDeniedHandler accessDeniedHandler;

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf()
            .disable()
            .exceptionHandling()
            .authenticationEntryPoint(new Http403ForbiddenEntryPoint() {
            })
        .and()
            .authenticationProvider(getProvider())
            .formLogin()
            .loginProcessingUrl("/login")
            .successHandler(new AuthentificationLoginSuccessHandler())
            .failureHandler(new SimpleUrlAuthenticationFailureHandler())
        .and()
            .logout()
            .logoutUrl("/logout")
            .logoutSuccessHandler(new AuthentificationLogoutSuccessHandler())
            .invalidateHttpSession(true)
        .and()
            .authorizeRequests()
            .antMatchers("/login").permitAll()
            .antMatchers("/logout").authenticated()
            .antMatchers("/management/student*","/management/professor*").hasRole("ADMIN")
            .antMatchers("/management/rooms*").hasRole("PROFESSOR");
    }

    private class AuthentificationLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                Authentication authentication) throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_OK);
        }
    }

    private class AuthentificationLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
        @Override
        public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
                Authentication authentication) throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_OK);
        }
    }

    @Bean
    public AuthenticationProvider getProvider() {
        AuthProvider provider = new AuthProvider();
        provider.setUserDetailsService(userDetailsService);
        return provider;
    }

有什么建议吗?

0 个答案:

没有答案