SpringBoot 集成 OAuth2 系列二(password篇)

1,982 阅读2分钟

参考文档:docs.spring.io/spring-secu…

完整代码:gitee.com/mayanze123/…

系列文章:

SpringBoot 集成 OAuth2 系列一(最简单配置篇)

SpringBoot 集成 OAuth2 系列二(password篇)

springBoot集成oAuth2,系列三(UserDetailsService篇)

springBoot集成oAuth2,系列四(前后端分离web页面中使用oauth2跨域问题篇)

springBoot集成oAuth2,系列五(下载等location.href 如何使用token)

springBoot集成oAuth2,系列六(如何获取refresh_token)

springBoot集成oAuth2,系列七(根据refresh_token获取access_token)

springBoot集成oAuth2,系列八(使用redis存储token的时候,报错: java.lang.NoSuchMethodError: org.springframework.data.redis.connection.RedisConnection.set)

前言

此篇文章是springboot 集成oauth2 用户密码授权基础篇,大部分web还是使用的用户密码登录页面,尤其是前后端分离的可以参考下

效果如下:

1.直接访问api接口

curl --location --request GET 'http://127.0.0.1:8080/whoami?name=mayanze'

image.png

2.获取token(有点小抽象,官方文档例子,不懂看下面)

curl --location --request POST 'http://first-client:noonewilleverguess@localhost:8080/oauth/token?scope=resource:read&grant_type=password&username=myz&password=myz'

image.png

不好理解看这里(与上面意思一致)

curl --location --request POST 'http://localhost:8080/oauth/token?scope=resource:read&grant_type=password&username=myz&password=myz' \
--header 'Authorization: Basic Zmlyc3QtY2xpZW50Om5vb25ld2lsbGV2ZXJndWVzcw=='

image.png

3.拿token访问api接口

curl --location --request GET 'http://127.0.0.1:8080/whoami?name=mayanze' \
--header 'Authorization: Bearer dfVidwI31Nyzy-3dOXH8M82Xr6k'

image.png

代码实现

可以参考完整代码:gitee.com/mayanze123/…

1.在上一基础篇上加 WebSecurityConfig

package com.example.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.ArrayList;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("myz")
                .password(passwordEncoder().encode("myz"))
                .authorities(new ArrayList<>(0));
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //所有请求必须认证
        http.authorizeRequests().anyRequest().authenticated();
    }
}

2.在上一基础篇上加 AuthorizationServerConfig

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;

@Configuration
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;//密码模式需要注入认证管理器

    @Autowired
    public PasswordEncoder passwordEncoder;

    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                .inMemory()
                .withClient("first-client")
                .secret(passwordEncoder.encode("noonewilleverguess"))
                .scopes("resource:read")
                .authorizedGrantTypes("password","authorization_code");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.authenticationManager(authenticationManager);
    }
}