User Roles Spring Data Rest Spring security

限于喜欢 提交于 2020-05-29 12:26:33

问题


I have an error that I dont really understand. I didn't find any tutorial that explain why it doesn't work. I have this spring boot application using spring security.

When I make this POST request : http://localhost:8181/roles body:

{
    "name":"ROLE_USER"
} 

it works fine.

When I make this POST request : http://localhost:8181/users body:

 {
    "username":"user",
    "password":"pass",
    "roles":[
      "http://localhost:8181/roles/1"
    ]
} 

it works fine

But when I make this GET request: http://localhost:8181/users with right credentials (username:user, password:pass)

it returns :

{
  "timestamp": "2020-04-22T15:04:55.032+0000",
  "status": 403,
  "error": "Forbidden",
  "message": "Forbidden",
  "path": "/users"
}

I don't know why it returns a 403.

PS: All requests are done on Postman

UnoApplication.java

package com.example.Uno;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@SpringBootApplication
public class UnoApplication {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }

    public static void main(String[] args) {
        SpringApplication.run(UnoApplication.class, args);
    }
}

User.java

package com.example.Uno.entity;

import lombok.Data;

import javax.persistence.*;
import java.io.Serializable;
import java.util.*;

@Data
@Entity

public class User implements Serializable {

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

    private String username;
    private String password;


    @ManyToMany(mappedBy = "users",targetEntity = Role.class,cascade = {CascadeType.MERGE,CascadeType.PERSIST}, fetch = FetchType.EAGER)
    private Set<Role> roles = new HashSet<>();


}

Role.java

package com.example.Uno.entity;

import lombok.Data;

import javax.persistence.*;
import java.io.Serializable;
import java.util.*;

@Data
@Entity

public class Role implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @ManyToMany(cascade = {CascadeType.MERGE,CascadeType.PERSIST}, fetch = FetchType.LAZY)
    private Set<User> users = new HashSet<>();


}


MyUserDetails.java

package com.example.Uno.entity;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;


public class MyUserDetails implements UserDetails {

    private String username;
    private String password;
    private List<GrantedAuthority> grantedAuthorities;

    public MyUserDetails(com.example.Uno.entity.User user){
        this.username = user.getUsername();
        this.password = user.getPassword();
        for (Role r: user.getRoles()){
            grantedAuthorities.add(new SimpleGrantedAuthority(r.getName()));
        }

    }


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return grantedAuthorities;
    }

    @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 true;
    }
}

UserRepository.java

package com.example.Uno.repository;


import com.example.Uno.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import java.util.Optional;


@RepositoryRestResource
public interface UserRepository extends JpaRepository<User,Long> {

    User findUserByUsername(String s);

}

RoleRepository.java

package com.example.Uno.repository;

import com.example.Uno.entity.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource
public interface RoleRepository extends JpaRepository<Role,Long> {
    Role findRoleByName(String name);
}

MyUserDetailsService.java

package com.example.Uno.service;

import com.example.Uno.entity.MyUserDetails;
import com.example.Uno.entity.User;
import com.example.Uno.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


@Service
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        User user = userRepository.findUserByUsername(s);
        return new MyUserDetails(user);
    }
}

SecurityConfig.java

package com.example.Uno.config;

import com.example.Uno.service.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

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

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.POST,"/users");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
                .antMatchers("/users").hasRole("USER")
                .anyRequest().permitAll().and().httpBasic();
    }
}

Thank you for your time.

EDIT

I added this line in my application.properties: logging.level.org.springframework.security=DEBUG

and when I make the previous GET Request, it look like this in the backend: Spring part 2 User Role


回答1:


So based on the log

com.example.Uno.entity.MyUserDetails@1c6f2612; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Not granted any authorities'

Your user details did not have any authorities, which means the method: findUserByUserName didn’t get any roles into the User Object. Or you need to query out the role separately with your other function: findRoleByName(), and set it to the userdetails.

you are on the right direction, and very close to the triumph!



来源:https://stackoverflow.com/questions/61370456/user-roles-spring-data-rest-spring-security

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!