Роли пользователей Spring Data Rest Безопасность Spring - PullRequest
2 голосов
/ 22 апреля 2020

У меня ошибка, которую я не совсем понимаю. Я не нашел ни одного учебника, объясняющего, почему он не работает. У меня есть это весеннее загрузочное приложение, использующее пружинную безопасность.

Когда я делаю этот запрос POST: http://localhost: 8181 / ролей тело:

{
    "name":"ROLE_USER"
} 

все работает нормально.

Когда я делаю этот POST-запрос: http://localhost: 8181 / users body:

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

отлично работает

Но когда я делаю этот GET-запрос: http://localhost: 8181 / users с правами доступа (имя пользователя: user, password: pass)

возвращает:

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

Я не знаю, почему возвращается 403.

PS: Все запросы выполняются почтальоном

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);
    }
}

Пользователь. 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<>();


}

Роль. 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();
    }
}

Спасибо за ваше время.

РЕДАКТИРОВАТЬ

Я добавил эту строку в моем application.properties: logging.level.org.springframework.security = DEBUG

и когда я делаю предыдущий запрос GET, он выглядит следующим образом: Spring, часть 2, роль пользователя

1 Ответ

0 голосов
/ 23 апреля 2020

Итак, основываясь на журнале

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'

Ваши данные пользователя не имеют каких-либо полномочий, что означает метод: findUserByUserName не получил никаких ролей в объекте пользователя. Или вам нужно запросить роль отдельно с помощью другой функции: findRoleByName () и установить для нее значение userdetails.

вы находитесь в правильном направлении и очень близки к триумфу!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...