简体   繁体   中英

How can I secure my Spring Data Rest endpoints using Spring Security?

I am working with a Spring application. All is well on the browser. I can login with existing users, needing to provide only my username and password. I can also sign-up with a new user, and afterwards login in with it.

I also have available some REST endpoints which I can call. I didn't define those endpoints manually. They were created automatically, because I am using the spring-boot-starter-data-rest dependency.

The URL of a REST request would look something like http://localhost:8182/api/v1/recipes .

I am trying to get a list of recipes using Postman. I would want to get an error message like "403 Forbidden", or something like that, because I didn't provide any credentials. Instead, I receive the HTML code of the login page, and a status code of "200 OK".

This applies also after I provide the username and password as request headers (maybe I need to use another way to provide the credentials)

user:user
password:password

The following list contains a few snippets of code, to show everything I wrote in the project that is regarding the security bit of the application:

  1. The first snippet of code represents the SecurityConfig class from my project:

     @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter{ @Autowired private UserService userService; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{ auth.userDetailsService(userService).passwordEncoder(User.PASSWORD_ENCODER); } @Override public void configure(WebSecurity web) throws Exception{ web.ignoring().antMatchers("/css/**"); web.ignoring().antMatchers("/images/**"); web.ignoring().antMatchers("/js/**"); } @Override protected void configure(HttpSecurity http) throws Exception{ http.authorizeRequests() .antMatchers("/sign-up").permitAll() .anyRequest() .hasRole("USER") .and() .formLogin() .loginPage("/login") .permitAll() .successHandler(loginSuccessHandler()) .failureHandler(loginFailureHandler()) .and() .logout() .permitAll() .logoutSuccessUrl("/login") .and() .csrf().disable(); } public AuthenticationSuccessHandler loginSuccessHandler(){ return (request, response, authentication) ->{ response.sendRedirect("/recipes/"); }; } public AuthenticationFailureHandler loginFailureHandler(){ return (request, response, exception) ->{ request.getSession().setAttribute("flash", new FlashMessage("Incorrect username and/or password. Try again.", FlashMessage.Status.FAILURE)); response.sendRedirect("/login"); }; } @Bean public EvaluationContextExtension securityExtension(){ return new EvaluationContextExtensionSupport() { @Override public String getExtensionId() { return "security"; } @Override public Object getRootObject(){ Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return new SecurityExpressionRoot(authentication) { }; } }; } } 
  2. The second is the User entity class:

      @Entity public class User implements UserDetails{ public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder(); @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull @Column(unique = true) @Size(min = 2, max = 20) private String username; @NotNull @Column(length = 100) @JsonIgnore private String password; @NotNull @Column(length = 100) @JsonIgnore private String matchingPassword; @Column(nullable = false) private boolean enabled; @OneToOne @JoinColumn(name = "role_id") @JsonIgnore private Role role; @ManyToMany(targetEntity = Recipe.class, fetch = FetchType.EAGER) @JoinTable(name = "users_favorite_recipes", joinColumns = @JoinColumn(name="user_id"), inverseJoinColumns = @JoinColumn(name = "recipe_id")) private List<Recipe> favoritedRecipes = new ArrayList<>(); @JsonIgnore @OneToMany(mappedBy = "user", cascade = CascadeType.ALL) private List<Recipe> ownedRecipes = new ArrayList<>(); //constructor ... //getters and setters ... public void encryptPasswords(){ password = PASSWORD_ENCODER.encode(password); matchingPassword = PASSWORD_ENCODER.encode(matchingPassword); } @Override public Collection<? extends GrantedAuthority> getAuthorities() { List<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(role.getName())); return authorities; } @Override public String getPassword() { return password; } @Override public String getUsername() { return username; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return enabled; } } 
  3. The third snippet represents an interface that extends the UserDetailsService:

     public interface UserService extends UserDetailsService{ UserDetails loadUserByUsername(String username); User findByUsername(String username); User registerNewUser(String username, boolean enabled, String password, String matchingPassword); void save(User user); List<User> findAll(); } 
  4. The fourth and final snippet is an implementation of the previous interface (UserService):

     @Component @ComponentScan public class UserServiceImpl implements UserService{ @Autowired private UserDao userDao; @Autowired private RoleDao roleDao; @Override public User findByUsername(String username) { User user = userDao.findByUsername(username); Hibernate.initialize(user.getFavoritedRecipes()); return user; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{ User user = userDao.findByUsername(username); if(user == null){ throw new UsernameNotFoundException( username + " was not found" ); } return user; } @Override public void save(User user) { userDao.save(user); } @Override public User registerNewUser(String username, boolean enabled, String password, String matchingPassword) { return userDao.save(new User(username, enabled, password, matchingPassword)); } @Override public List<User> findAll() { return userDao.findAll(); } } 

What must I modify in this situation, in order to have a functional REST API authorization ?

From what I understand you have a RESTful API (with no UI ), if that is true you can update SecurityConfig # configure(HttpSecurity http) method replace this :

@Override
protected void configure(HttpSecurity http) throws Exception{
    http.authorizeRequests()
            .antMatchers("/sign-up").permitAll()
            .anyRequest()
            .hasRole("USER")
            .and()
            .formLogin()
            .loginPage("/login")
            .permitAll()
            .successHandler(loginSuccessHandler())
            .failureHandler(loginFailureHandler())
            .and()
            .logout()
            .permitAll()
            .logoutSuccessUrl("/login")
            .and()
            .csrf().disable();
}

By This :

@Override
    protected void configure(HttpSecurity http) throws Exception {
            http
                .cors()
                .and()
                .csrf()
                .disable()
                .exceptionHandling()
                .authenticationEntryPoint((request, response, exc) ->
                        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You are not authorized to access this resource."))
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // Array of String that contain's all endpoints you want secure
                .antMatchers(ENDPOINTS_TO_SECURE).access("hasAnyRole('ROLE_USER')")
                // Array of String that contain's all endpoints you want to permit
                .antMatchers(WHITE_LIST).permitAll()
                .anyRequest()
                .authenticated();
        // disable page caching
        http.headers().cacheControl();
    }

You need to configure your own authentication entry point, to get 403 messages, you can use Http403ForbiddenEntryPoint.

Example:.

@RestController
public class Controller {

    @GetMapping("/test")
    public String test() {
        return "test";
    }
}

Adding .exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint()) :

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.authorizeRequests()
                .antMatchers("/sign-up").permitAll()
                .anyRequest()
                .hasRole("USER")
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll()
                .logoutSuccessUrl("/login")
                .and()
                .csrf().disable()
                .exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint());
    }
}

Now when I try to access http://localhost:8080/test , I get 403 Access Denied message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM