Это проект безопасности с весенней загрузкой.Весь мой проект работает совершенно нормально, однако я не могу получить доступ к маршрутам на основе ролей.Когда я пытаюсь, я получаю 403 запрещенную ошибку.Пожалуйста, помогите мне решить эту проблему.
package csse.users;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class UserService {
private UserDAO repo;
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
public UserService(UserDAO repo, BCryptPasswordEncoder bCryptPasswordEncoder) {
this.repo = repo;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
private List<ApplicationUser> users;
//register
String register(ApplicationUser user) {
users=repo.findAll();
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
String d=dateFormat.format(date);
//System.out.println(d); //2016/11/16 12:08:43
if((!user.getAddress().isEmpty()) && (!user.getEmail().isEmpty()) && (!user.getEmp_ID().isEmpty()) && (!user.getEmp_type().isEmpty())
&& (!user.getEmp_type().isEmpty()) && (!user.getFirstname().isEmpty()) && (!user.getLastname().isEmpty()) && (!user.getPassword().isEmpty())
&& (!user.getPhone().isEmpty()) && (!user.getUsername().isEmpty()) && (user.getRoles()!=null) && (!user.getRoles().isEmpty())) {
String usid=user.getEmp_ID();
String usemail=user.getEmail();
String ususn=user.getUsername();
if(!(users.toString().matches("\\[.*\\b" + usid + "\\b.*]"))) {
if(!(users.toString().matches("\\[.*\\b" + usemail + "\\b.*]"))) {
if(!(users.toString().matches("\\[.*\\b" + ususn + "\\b.*]"))) {
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
user.setCreatedDate(d);
user.setlastLogin("00/00/0000 00:00:00");
user.setModifiedDate(d);
repo.save(user);
return user.toString();
} else{ return "Username exists";}
} else{ return "Email exists";}
} else{ return "EmployeeID exists";}
} else{ return "fill all fields";}
}
//get all users
@Secured({"ROLE_ADMIN"})
List<ApplicationUser> all(){
return repo.findAll();
}
}
// Класс Contoller, расширяющий пользователей пакета услуг;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/users")
public class UserHttpController {
private UserService service;
@Autowired
public UserHttpController(UserService service, UserDAO repo) {
this.service = service;
}
@PostMapping("/signup")
public String signUp(@RequestBody ApplicationUser user) {
return service.register(user);
}
@GetMapping("/list")
public List<ApplicationUser> list() {
return service.all();
}
@GetMapping("/{username}")
ApplicationUser details(@PathVariable(value="username")String username) {
return service.findByUsername(username);
}
}
// класс веб-безопасности
package csse.auth;
import static csse.auth.SecurityConstants.SIGN_UP_URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@Configuration
@EnableWebSecurity // Enable security config. This annotation denotes config for spring security.
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
private UserDetailsServiceImpl UsersService;
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
public WebSecurityConfig(UserDetailsServiceImpl UsersService, BCryptPasswordEncoder bCryptPasswordEncoder) {
this.UsersService = UsersService;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
@Override
protected void configure(HttpSecurity http) throws Exception{
http
.cors()
.and()
.csrf().disable()
.authorizeRequests() // authorization requests config
.antMatchers("/users/list").hasRole("ADMIN")
.antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
.antMatchers("/v2/api-docs",
"/configuration/ui",
"/swagger-resources",
"/swagger-resources/configuration/security",
"/swagger-resources/configuration/ui",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**").permitAll()
.anyRequest().authenticated() // Any other request must be authenticated
.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager()))
// this disables session creation on Spring Security
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
// Spring has UserDetailsService interface, which can be overriden to provide our implementation for fetching user from database (or any other source).
// The UserDetailsService object is used by the auth manager to load the user from database.
// In addition, we need to define the password encoder also. So, auth manager can compare and verify passwords.
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(UsersService).passwordEncoder(bCryptPasswordEncoder);
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
}
// Класс приложения
package csse;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@SpringBootApplication
@ComponentScan("csse")
public class Application {
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
// две записи пользователя в моей базе данных
{
"_id": {
"$oid": "5bab65cbf835f23eb06b0eab"
},
"emp_ID": "A5010",
"emp_type": "Site Manager",
"firstname": "Markian",
"lastname": "Bule",
"address": "Negombo",
"email": "mark.b@gmail.com",
"phone": "0777797531",
"username": "MarkB",
"password": "$2a$10$ODxFJvz6ZsfgRWELGgXmdeC0I9kZXHHIf9PHwpQZx2zENCn4lwlLO",
"roles": "ADMIN",
"createdDate": "26/09/2018 16:26:11",
"lastLogin": "00/00/0000 00:00:00",
"modifiedDate": "26/09/2018 16:26:11",
"_class": "csse.users.ApplicationUser"
}
{
"_id": {
"$oid": "5bac4e73f835f23674fe25e7"
},
"emp_ID": "A4000",
"emp_type": "Site Manager",
"firstname": "Shan",
"lastname": "Perera",
"address": "Chilaw",
"email": "shan.p@gmail.com",
"phone": "0995534287",
"username": "shan.p",
"password": "$2a$10$R48p6mozw8BemH1emt9h3.9hOSCKb9pqwRNp2NDxk3hAQsGjp1hIO",
"roles": "USER",
"createdDate": "27/09/2018 08:58:51",
"lastLogin": "00/00/0000 00:00:00",
"modifiedDate": "27/09/2018 08:58:51",
"_class": "csse.users.ApplicationUser"
}