我实际上正在通过boot和rest api学习Spring Security。我已经编写了用于保护我的api的代码,但是出现了错误。我搜索了很多,但没有解决方案对我有用。
这是我的应用程序的屏幕截图
我的一个控制器中有以下代码:
@RestController
@RequestMapping("secured")
public class LoginController {
@PreAuthorize("hasAnyRole('ADMIN')")
@GetMapping(produces = MediaType.TEXT_PLAIN_VALUE, value = "/all")
public String hello() {
return "hello Youtube";
}
@PreAuthorize("hasAnyRole('user')")
@GetMapping("/a")
public @ResponseBody String securedHello() {
return "Secured Hello";
}
}
SecurityConfig类
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableJpaRepositories(basePackageClasses=UserDetailsService.class)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws
Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(getPasswordEncoder());
//auth.authenticationProvider(authenticationProvider());
}
private PasswordEncoder getPasswordEncoder() {
return new PasswordEncoder() {
@Override
public boolean matches(CharSequence charSequence, String s) {
return true;
}
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
};
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers("/secured/**").authenticated().anyRequest().hasAnyRole("ADMIN").and()
.formLogin().permitAll();
}
application.properties
server.port:8969
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/pharmaplussecurity
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.properties.hibernate.dialect =org.hibernate.dialect.MySQL5Dialect
spring.application.name: PharmaPlus-security
spring.jpa.show-sql=true
server.servlet.session.timeout=300s
server.error.whitelabel.enabled=false
spring.jpa.open-in-view=false
UserServiceImpl类
@Service
public class UserServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<User> optionalUser = userRepository.findByUsername(username);
optionalUser
.orElseThrow(() -> new UsernameNotFoundException("Username Not Found"));
return optionalUser
.map(CustomUserDetails::new).get();
}
}
CustomeUserDetails类
public class CustomUserDetails extends User implements UserDetails {
public CustomUserDetails(final User user) {
super(user);
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getRoles()
.stream()
.map(role -> new SimpleGrantedAuthority("ROLE_"+role.getRole()))
.collect(Collectors.toList());
}
@Override
public String getPassword() {
return super.getPassword();
}
@Override
public String getUsername() {
return super.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
PharmaPlusSecurity类
@EntityScan("com.pk.pharmasecurity.entity")
@EnableJpaRepositories("com.pk.pharmasecurity.repository")
@ComponentScan(basePackageClasses = SecurityConfiguration.class)
@SpringBootApplication
@EnableEurekaClient
public class PharmaPlusSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(PharmaPlusSecurityApplication.class, args);
}
}
还有pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<!-- <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency> -->
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>