spring - 缺少授权类型错误

标签 spring spring-boot oauth-2.0

我只是想学习 OAuth。我写了一些代码来测试它。当我提交请求时我得到 { “错误”:“无效请求”, "error_description": "缺少授权类型" }

postman 错误。

import java.util.Optional;

//import static org.assertj.core.api.Assertions.tuple;

import java.util.stream.Stream;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.springframework.security.core.userdetails.User;

//import org.omg.PortableInterceptor.ACTIVE;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
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.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.stereotype.Service;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@SpringBootApplication
public class SpringAuthServiceApplication {

    @Bean
    CommandLineRunner clr(AccountRepository accountRepository){
        return args -> {
            Stream.of("name1, password1", "name2, password2", "name3, password3", "name4, password4")
            .map(tpl -> tpl.split(",") )
            .forEach(tpl -> accountRepository.save(new Account(tpl[0], tpl[1], true)));
        };


    }

    public static void main(String[] args) {
        SpringApplication.run(SpringAuthServiceApplication.class, args);
    }
}


@Configuration
@EnableAuthorizationServer
class AuthServiceConfiguration extends AuthorizationServerConfigurerAdapter{
    private final AuthenticationManager authenticationManager;

    public AuthServiceConfiguration(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
        .inMemory()
        .withClient("html5")
        .secret("password")
        .authorizedGrantTypes("password")
        .scopes("openid");

    }

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



}


@Service
class AccountUserDetailService implements UserDetailsService{

    private final AccountRepository accountRepository;

    public AccountUserDetailService(AccountRepository accountRepository) {
//      super();
        this.accountRepository = accountRepository;
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO Auto-generated method stub
        return accountRepository.findByUsername (username)
                .map(account -> new User(account.getUsername(),
                        account.getPassword(), account.isActive(), account.isActive(), account.isActive(), account.isActive(),
                        AuthorityUtils.createAuthorityList("ROLE_ADMIN", "ROLE_USER") )
                        )
                .orElseThrow(() -> new UsernameNotFoundException("Couldn't fine user name " + username + "!") ) ;
    }

    /*@Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return accountRepository.findByUsername(username)
                .map(account -> {
                    boolean active = account.isActive();
                    return new User(
                            account.getUsername(),
                            account.getPassword(),
                            active, active, active, active,
                            AuthorityUtils.createAuthorityList("ROLE_ADMIN", "ROLE_USER"));
                })
                .orElseThrow(() -> new UsernameNotFoundException(String.format("username %s not found!", username)));
    }*/

}



interface AccountRepository extends JpaRepository<Account, Long>{
    Optional<Account> findByUsername(String username); 
}



@Data 
@NoArgsConstructor
@AllArgsConstructor
@Entity
class Account{

    public Account(String username, String password, boolean active) {
        //super();
        this.username = username;
        this.password = password;
        this.active = active;
    }

    @GeneratedValue @Id
    private long id; 
    private String username, password;
    private boolean active;


}

这是我在 postman 中发送的内容:

在标题选项卡中: 内容类型:application/json 授权:基本aHRtbDU6cGFzc3dvcmQ=

在“授权”选项卡中: 类型是基本身份验证 用户名:html5 密码:密码

正文选项卡,选定的表单数据并发送以下内容:

用户名:用户名 密码: 密码1 grant_type:密码 范围:openid 客户端 ID:html5 client_secret:密码

enter image description here

enter image description here

enter image description here

最佳答案

OAuth2 正在请求正文中查找查询字符串形式的参数,又名 application/x-www-form-urlencoded

将您的 Content-Type 更改为 application/x-www-form-urlencoded 并检查 x-www-form-urlencoded 而不是表单数据

关于spring - 缺少授权类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44962573/

相关文章:

azure - Microsoft OAuth 2.0 客户端凭据 - 即使在 Azure 上获得管理员同意,也无法检索范围权限

java - Grails:是什么导致 NameRegistry.getIdFor 中出现 ArrayIndexOutOfBoundsException?

spring - Kotlin - SpringApplicationBuilder 中的扩展运算符

python - Gdata python 谷歌应用程序身份验证

c# - 尝试使用身份验证生成器的 AddTwitter() 时找不到定义

java - Spring Activity 将于元旦起火

java - Spring Cache Evict 不起作用

java - Spring 集成;在复制完成之前复制服务拾取的文件

java - Spring @ConfigurationProperties 解析器忽略外部化属性

java - Spring Boot @Mapper Bean 创建问题 : Application Failed to start. 错误:考虑定义 Type 的 bean