Spring boot security rest basic Authentication example
Posted chenqr
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring boot security rest basic Authentication example相关的知识,希望对你有一定的参考价值。
1. Maven dependency
pom.xml
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.5.RELEASE</version> <relativePath /> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> </dependencies>
2. Configure WebSecurityConfigurerAdapter
SecurityConfig.java
package com.howtodoinjava.rest.config; 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.WebSecurityConfigurerAdapter; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter @Override protected void configure(HttpSecurity http) throws Exception http .csrf().disable() .authorizeRequests().anyRequest().authenticated() .and() .httpBasic(); @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception auth.inMemoryAuthentication() .withUser("admin") .password("nooppassword") .roles("USER");
3. Spring boot security rest basic authentication demo
3.1. REST API
EmployeeController.java
@RestController @RequestMapping(path = "/employees") public class EmployeeController @Autowired private EmployeeDAO employeeDao; @GetMapping(path="/", produces = "application/json") public Employees getEmployees() return employeeDao.getAllEmployees();
3.2. Access rest api without ‘authorization’ header
get http://localhost:8080/employees/
3.3. Access rest api with ‘authorization’ header
HTTP GET http://localhost:8080/employees/ with header
以上是关于Spring boot security rest basic Authentication example的主要内容,如果未能解决你的问题,请参考以下文章
如何将 Spring Security 与 Spring Boot Rest API 一起使用?
Spring Boot 2 + Spring Security 5 + JWT 的 Restful简易教程!
Spring Security 自定义登录功能不适用于 Spring Boot 和 REST api
Angular 2 + CORS + 带有 Spring Security 的 Spring Boot Rest Controller
使用spring boot、jpa和security的多用户restful api
Spring boot:无法从另一个 Origin 访问安全资源 - CORS - Spring Security - Spring data rest