Я новичок в Spring Security и создавал простое приложение для проверки подлинности и авторизации.Я использую в памяти базы данных.Даже когда я даю правильные учетные данные, я получаю ошибку 401 «Bad Credentials».Также я использовал функцию allowAll () на некоторых конечных точках отдыха, но я также получаю приглашение для входа в систему на этих конечных точках.Я попытался очистить историю браузера и кеш, но пока безуспешно.Пожалуйста помоги.Я прилагаю код.
SecurityConfig.java
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
//Authentication using In Memory Database
public void configureGlobal(AuthenticationManagerBuilder authenticationManagerBuilder)throws Exception{
authenticationManagerBuilder.inMemoryAuthentication()
.withUser("user").password("{noop}pass123").authorities("ROLE_USER")
.and()
.withUser("admin").password("{noop}pass123").authorities("ROLE_USER","ROLE_ADMIN");
}
//Authorization
@Override //Overriding configure to use HttpSecurity for web based HTTP requests
public void configure(HttpSecurity httpSecurity)throws Exception{
httpSecurity.
authorizeRequests()
.antMatchers("/protectedbyuserrole*").hasRole("USER")
.antMatchers("/protectedbyadminrole*").hasRole("ADMIN")
.antMatchers("/","/notprotected").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
SpringSecurityApplication.Java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
@SpringBootApplication
@ComponentScan({"com.example.demo","controller"})
@Import({SecurityConfig.class})
public class SpringSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSecurityApplication.class, args);
}
}
TestSecurityController.Java
package com.example.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestSecurityController {
@RequestMapping("/")
public String Hello() {
return "Hello World!! ";
}
@RequestMapping("/notprotected")
public String HelloAgain() {
return "Hello from a non protected user!! ";
}
@RequestMapping("/protectedbyuserrole")
public String HelloUser() {
return "Hello User Role!! ";
}
@RequestMapping("/protectedbyadminrole")
public String HelloAdmin() {
return "Hello Admin Role!! ";
}
}
POM.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.19.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>SpringSecurity-1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringSecurity-1</name>
<description>SpringSecurity for Authentication and Authorization</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
QUERIES
Также дайте мне знатькак использовать простые пароли, которые я могу использовать в почтальоне.Должен ли я использовать {noop} или просто написать пароль, например .password ("pass123").
Должен ли я использовать звездочку * или ** в .antmatchers ()
Я попробовал этоиспользуя также Postman и Firefox.Одна и та же ошибка везде. ПОСТМАНСКИЙ СКРИНШОТ