Spring安全性,基于角色的访问

时间:2018-10-01 05:49:20

标签: mongodb spring-mvc spring-boot security-roles jwt-auth

这是Spring Boot安全项目。我的整个项目都工作正常,但是我无法根据角色访问路线。当我尝试获取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"
 }

0 个答案:

没有答案
相关问题