我试图将spring oauth2(基于java的配置而不是引导)与angular 6集成,
我的WebSecurityConfigurerAdapter.java文件是:
package com.novowash.authentication;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class OAuth2SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private ClientDetailsService clientDetailsService;
@Autowired
NovoAuthenticationProvider novoAuthenticationProvider;
@Autowired
UserDetailsServiceImpl userDetailsServiceImpl;
@Autowired
private PasswordEncoder userPasswordEncoder;
@Autowired
@Qualifier("dataSource")
DataSource dataSource;
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
/*auth.inMemoryAuthentication()
.withUser("bill").password("abc123").roles("ADMIN").and()
.withUser("bob").password("abc123").roles("USER");*/
auth.authenticationProvider(novoAuthenticationProvider);
// auth.userDetailsService(userDetailsServiceImpl).passwordEncoder(userPasswordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and()
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS,"/oauth/token").permitAll()
.antMatchers("/signup").permitAll()
.anyRequest().authenticated()
.and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@Bean
@Autowired
public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore){
TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
handler.setTokenStore(tokenStore);
handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
handler.setClientDetailsService(clientDetailsService);
return handler;
}
@Bean
@Autowired
public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore);
return store;
}
}
我的身份验证提供程序是:
package com.novowash.authentication;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import com.novowash.Enums.CommonEnums;
import com.novowash.model.User;
import com.novowash.service.UserService;
/**
* @author manish
*
* This Class is responsible for authentication and
* access control of users to cube root Admin module over http in extension of AuthenticationProvider interface of Spring web framework .
*
*/
@Component("novoAuthenticationProvider")
public class NovoAuthenticationProvider implements AuthenticationProvider {
private static final Logger logger = Logger.getLogger(NovoAuthenticationProvider.class);
@Autowired UserService userService;
/* (non-Javadoc)
* @see org.springframework.security.authentication.AuthenticationProvider#authenticate(org.springframework.security.core.Authentication)
*/
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
try {
logger.debug( "ImageVideoAuthenticationProvider.authenticate() authentication.getPrincipal(): " + authentication.getPrincipal());
logger.debug( "ImageVideoAuthenticationProvider.authenticate() authentication.getCredentials(): " + authentication.getCredentials());
String userName = authentication.getPrincipal().toString();
String password = authentication.getCredentials().toString();
User user = userService.findUserByMobile(userName);
if (user == null) {
throw new UsernameNotFoundException(String.format(URLEncoder.encode("Invalid Email OR password", "UTF-8"), authentication.getPrincipal()));
}
if (CommonEnums.STATUS.INACTIVE.ID == user.getStatus()) {
throw new UsernameNotFoundException(String.format(URLEncoder.encode("You are not active", "UTF-8"), authentication.getPrincipal()));
}
if (CommonEnums.STATUS.BLOCK.ID == user.getStatus()) {
throw new UsernameNotFoundException(String.format(URLEncoder.encode("You are blocked. Please contact admin", "UTF-8"), authentication.getPrincipal()));
}
List<String> roles=null;
if(user != null){
roles= userService.getUserRoles(user.getId());
}
List<GrantedAuthority> grantList= new ArrayList<GrantedAuthority>();
if(roles!= null) {
for(String role: roles) {
// ROLE_USER, ROLE_ADMIN,..
GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + role);
grantList.add(authority);
}
}
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, password, grantList);
return token;
} catch (Exception e) {
logger.error( "Error in ImageVideoAuthenticationProvider.authenticate()", e);
throw new AuthenticationServiceException(e.getMessage());
}
}
/* (non-Javadoc)
* @see org.springframework.security.authentication.AuthenticationProvider#supports(java.lang.Class)
*/
public boolean supports(Class<?> clazz) {
return clazz.equals(UsernamePasswordAuthenticationToken.class);
}
}
import { HttpClient, HttpHeaders, HttpParams } from "@angular/common/http";
import { Inject, Injectable } from "@angular/core";
import { OAuthService } from "angular-oauth2-oidc";
import { environment } from "../../environments/environment";
import { Observable } from "rxjs/Observable";
import { map, combineLatest } from 'rxjs/operators';
@Injectable()
export class ROPCService {
private _user: any;
constructor(private httpClient: HttpClient, private oauthService: OAuthService) {}
public async login(username: string, password: string) {
debugger;
const body = new HttpParams()
.set('username', username)
.set('password', password)
.set('grant_type', environment.auth.grantType);
const headers = new HttpHeaders()
.set("Content-type", "application/x-www-form-urlencoded; charset=utf-8")
.set("Authorization", "Basic d2ViOnNlY3JldA==");
this.httpClient
.post(this.oauthService.tokenEndpoint, body.toString(), {headers:headers})
.pipe(map((res: any) => {
debugger;
})).subscribe(
data => {
debugger;
},
err => {
debugger;
}
)
}
public logOut() {
if (this.oauthService.getRefreshToken() === null) {
return;
}
const refreshToken = this.oauthService.getRefreshToken();
const accessToken = this.oauthService.getAccessToken();
this.oauthService.logOut(true);
const body = new HttpParams().set("client_id", this.oauthService.clientId).set("refresh_token", refreshToken);
return this.httpClient.post(this.oauthService.logoutUrl, body.toString(), {
headers: new HttpHeaders().set("Content-Type", "application/x-www-form-urlencoded"),
});
}
public get user() {
return this._user;
}
public set user(user) {
this._user = user;
}
}
后端出现错误:
它与您突出显示的错误所说的完全一致。您发送的请求方法是GET,但它需要一个选项方法。
它在OAuth2SecurityConfig
中配置:
.antMatchers(HttpMethod.OPTIONS,"/oauth/token").permitAll()
把它改成GET,它应该会起作用。
.antMatchers(HttpMethod.GET,"/oauth/token").permitAll()
我试图使用spring boot oauth2来完成无状态身份验证和授权。然而,我正在努力工作。 下面是我的代码: 授权配置: 资源服务器配置: 控制器: 我可以用邮递员拿到访问令牌。我在标题中使用相同的访问令牌来获取用户详细信息,例如。但是,我会得到登录页面html响应,下面是登录控制台: 但是,当我第一次调用以获取对的访问令牌时,似乎已经通过了身份验证: 可能是我配置错误。我在这里漏掉了什么?
下面是我的WebSecurityConfig.java文件: 我启用了调试日志,堆栈跟踪如下所示。
通过使用以下curl命令,我能够访问令牌并获得以下响应curl用户名:password@machinename:11002/appName/oauth/token-d grant\u type=password-d username=loginFormUserID-d password=loginFormUserPassword 响应:{“实体\ id”:9,“实体\类型”:“刷新\标记”:“ey
昨天我在编码,当我做提交到一个回购,我不能这样做,因为,gitlab给我发送了两个消息。 这条消息出现在我试图promise的时刻 null
我在Windows 10 Pro x64上使用GitLab Community Edition 9.1.3 2E4E522。使用Git客户端。
于是我在这里看到:https://firebase . Google . com/docs/auth/web/account-linking # link-auth-provider-credentials-to-a-user-account现在可以在Firebase中链接用户账号了。我还看到Firebase提供了匿名认证的功能,它为一个用户创建一个用户会话,不需要任何凭证。 在我们的应用程序中,