我正在使用Spring安全性设置OAuth2.0授权服务器.我想知道在OAuth2.0授权服务器启动并运行后是否有办法动态注册OAuth2.0客户端?
基本上,我知道我可以在配置OAuth2.0服务器时通过扩展AuthorizationServerConfigurerAdapter和覆盖configure方法来注册客户端,以在内存中添加客户端详细信息.但是,这种方式客户端已预先注册,我想知道如何动态添加客户端详细信息.
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// @formatter:off
clients.inMemory()
.withClient(CLIENT_ID)
.secret(CLIENT_SECRET)
.authorizedGrantTypes("authorization_code", "implicit")
.redirectUris("http://junk/")
.scopes("cn")
.accessTokenValiditySeconds(600);
// @formatter:on
}
这是我正在做的一个实践项目,学习 Spring Security 和 OAuth2。
链接到项目的 zip - https://drive.google.com/open?id=0BxsYBg5XwboXdkpUdkhXWUd1Vmc
一旦我添加了以下类,我的自动装配服务就会失败:( 它给出了 NullPointerException。
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return new OAuth2MethodSecurityExpressionHandler();
}
}
Run Code Online (Sandbox Code Playgroud)
我userService在下面的休息控制器中得到 NullPointerException 。
@RestController
@RequestMapping("/api/user")
public class UserCtrl {
@Autowired
@Qualifier("userService")
UserService userService;
@PreAuthorize("#oauth2.hasScope('write')")
@RequestMapping(method=RequestMethod.POST,consumes="application/json")
private @ResponseBody ResponseMessage registerUser(@RequestBody User user){
user.setUser_id(-1);
return userService.createUser(user);
}
@PreAuthorize("#oauth2.hasScope('none')")
@RequestMapping(method=RequestMethod.GET)
private @ResponseBody ResponseMessage loginUser(){
CustomUserDetails temp = (CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
System.out.println(temp.getUsername() + " logged in");
ResponseMessage message = userService.getUserByUsername(temp.getUsername());
if(message.getCode() …Run Code Online (Sandbox Code Playgroud) 我正在使用oauth2来访问第三方API.我可以获得访问令牌,但是当我尝试通过在请求标头中传递承载令牌来调用API时,它会给我401(未授权)错误.虽然当我尝试通过传递头文件(授权:承载)来通过POSTMAN来做它时效果很好.但它使用go无效.
这是代码示例.
url := "http://api.kounta.com/v1/companies/me.json"
var bearer = "Bearer " + <ACCESS TOKEN HERE>
req, err := http.NewRequest("GET", url, nil)
req.Header.Add("authorization", bearer)
client := urlfetch.Client(context)
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
writer.Write([]byte(body)) // Gives 401 Unauthorized error, though same works using POSTMAN
Run Code Online (Sandbox Code Playgroud) 在我的Spring Boot/OAuth2应用程序中,我试图通过我自己的OAuth2服务器登录用户,隐式流程使用以下URL:
http://example.com/api/oauth/authorize?response_type=token&client_id=example_client_id&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Flogin
Run Code Online (Sandbox Code Playgroud)
登录后,它会将用户重定向到以下网址:
http://localhost:8080/login#access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoyOTcsInVzZXJfbmFtZSI6ImFkbWluIiwic2NvcGUiOlsicmVh&token_type=bearer&expires_in=43199&scope=read%20write&user_id=297&jti=9d416117-0d08-4f4e-874d-3f31dbe7815f
Run Code Online (Sandbox Code Playgroud)
这是一个正确的行为,用户被重定向到带有#符号的网址而不是?..我的意思是:
http://localhost:8080/login?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoyOTcsInVzZXJfbmFtZSI6ImFkbWluIiwic2NvcGUiOlsicmVh&token_type=bearer&expires_in=43199&scope=read%20write&user_id=297&jti=9d416117-0d08-4f4e-874d-3f31dbe7815f
Run Code Online (Sandbox Code Playgroud)
如果没有 - 如何设置我的Spring应用程序OAuth2服务器,以便将用户重定向到正确的URL?
我按照本参考指南的步骤尝试安装adwords api for python:https://github.com/googleads/googleads-python-lib/wiki/API-access-using-own-credentials-( installed-application-flow )#步骤-2 ---设置-UP-的客户端库
一切都还可以,但在最后一步(6),我有一个问题.
我尝试运行代码:
from googleads import adwords
# Initialize the AdWords client.
adwords_client = adwords.AdWordsClient.LoadFromStorage()
Run Code Online (Sandbox Code Playgroud)
错误是:
> >pythonw -u "teste_adwords_api.py" Traceback (most recent call last): File "teste_adwords_api.py", line 3, in <module>
> adwords_client = adwords.AdWordsClient.LoadFromStorage() File "C:\Users\Flávio\Google Drive\BI Caiçara\Python\googleads\adwords.py",
> line 243, in LoadFromStorage
> cls._OPTIONAL_INIT_VALUES)) File "C:\Users\Flávio\Google Drive\BI Caiçara\Python\googleads\common.py", line 128, in
> LoadFromStorage
> 'Given yaml file, %s, could not be opened.' % path) googleads.errors.GoogleAdsValueError: Given yaml file,
> …Run Code Online (Sandbox Code Playgroud) 我想问一个问题,以确认我对如何使用范围和声明(角色)的理解.假设我有一个用户(具有只读权限的用户A,即适合的只读角色),Windows服务(具有只读访问权限的客户端A),MVC站点(具有完全访问权限的客户端B)和Web API.我希望具有完全访问权限和只读访问权限的用户和客户端访问Web API.
当客户端A连接到Web API时,它会传递一个包含Scope"sampleApi.read_only"的访问令牌,我可以使用[ScopeAuthorize("sampleApi.full)]或ScopeAuthorize("sampleApi.full,sampleApi.read_only")]用于微调可访问性的类和方法.没问题.
但是,当用户A登录时,他/她"继承"客户端B的范围.因此,访问令牌包含"sampleApi.full","sampleApi.read_only"和角色"read_only".
现在我在WebApi遇到了一个问题,我需要在被用户调用时采取不同的行动.在这种情况下,我忽略了范围并使用他/她的角色,用户获得"read_only"访问权限,这就是我想要的.
这是正确的,使用ScopeAuthorize属性不再有意义,我需要一个自定义混合属性来执行某些操作:
如果调用者是用户 - 然后使用角色来确定可访问性,则使用范围来确定可访问性
还是我完全被误解了?
我试图为Android应用程序制作oauth2。它几乎没有错误。
我的错误是重定向时没有授权之类的标题
MyCookieCode。当我登录时,它将发送授权。但是当我重定向时不起作用
public static Retrofit getLoginRetrofitOnAuthz() {
Retrofit.Builder builder = new Retrofit.Builder().baseUrl(ServerValue.AuthServerUrl).addConverterFactory(GsonConverterFactory.create());
if (LoginRetrofitAuthz == null) {
httpClientAuthz.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
String str = etUsername.getText().toString() + ":" + etPassword.getText().toString();
String Base64Str = "Basic " + Base64.encodeToString(str.getBytes(), Base64.NO_WRAP);
System.out.println(Base64Str);
Request request = chain.request().newBuilder().addHeader("Authorization", Base64Str).build();
return chain.proceed(request);
}
});
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
httpClientAuthz.cookieJar(new JavaNetCookieJar(cookieManager));
LoginRetrofitAuthz = builder.client(httpClientAuthz.build()).build();
}
return LoginRetrofitAuthz;
}
Run Code Online (Sandbox Code Playgroud)
您知道如何在重定向中保留标头吗?
使用Spring安全性来保护带有oauth的API时,范围和角色之间有什么区别吗?
例如,当使用基于非oauth的基于角色的授权时,我可能有一个以john该角色命名的用户admin.
如果我正在使用oauth,那么它似乎john只会有范围admin.
我是否正确地思考这个问题?
我不会在没有搜索和阅读文档的情况下问这个问题。到目前为止我花了2天。我确定我错过了什么。我正在尝试在驱动器电子表格上实施谷歌身份验证。我已经尝试了所有方法,但仍然收到错误消息(redirect_uri_mismatch)。基本上,我想要一个带有登录屏幕的侧面板。当用户允许访问时,用户单击按钮,auth magic 运行并重定向到另一个打印“成功”的 html。
创建凭据
2.1 客户端 ID:
131579675294-jc1c0ckuaa7n7ih7eevg19cisthgt00e.apps.googleusercontent.com
2.2 客户端密码:XaebFsC18qfMmcZJKgokLEYo
设置回调uri:
https://script.google.com/macros/d/MCgMJPIdD1bbeG1PsFaNug8uUifae5TWT/usercallback
项目密钥: MCgMJPIdD1bbeG1PsFaNug8uUifae5TWT
脚本 ID: 1DYEShH45-AtikbEwfAG8w9P7Y39FHhCB-nGHWHOW4mUtq5DZLvubDxev
据说 projectKey 已被弃用,而是需要使用脚本 ID,但两者都不起作用。
我使用 oauth2 所以我添加了外部库:1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF
说明:我的 gs 文件有以下代码。我有一个侧边栏,上面有一个按钮,单击时会调用 onSignIn()。我希望通过身份验证访问电子表格。首先,我想查看授权页面。接受后,我希望它重定向到一个页面,即 callback_uri 并显示一些简单的内容。但是它确实给了我错误。具有讽刺意味的是,我创建的端点浏览器链接工作并成功重定向。
端点浏览器链接
我究竟做错了什么?感谢您的帮助。谢谢。
var CLIENT_ID = '131579675294-jc1c0ckuaa7n7ih7eevg19cisthgt00e.apps.googleusercontent.com';
var CLIENT_SECRET = 'XaebFsC18qfMmcZJKgokLEYo';
function onSignIn() {
var service = getService();
if (!service.hasAccess()) {
var authorizationUrl = service.getAuthorizationUrl();
var template = HtmlService.createTemplate('<a href="<?= authorizationUrl ?>" target="_blank">Authorize</a>');
template.authorizationUrl = authorizationUrl;
var page = template.evaluate();
return HtmlService.createHtmlOutput( page);
}
} …Run Code Online (Sandbox Code Playgroud) 我有客户端服务器应用程序。我定位了麻烦,并且有这样的逻辑:
客户:
# -*- coding: utf-8 -*-
import requests
def fixing:
response = requests.post('http://url_for_auth/', data={'client_id': 'client_id',
'client_secret':'its_secret', 'grant_type': 'password',
'username': 'user', 'password': 'password'})
f = response.json()
data = {'coordinate_x': 12.3, 'coordinate_y': 8.4, 'address': u'\u041c, 12',
'products': [{'count': 1, 'id': 's123'},{'count': 2, 'id': 's124'}]}
data.update(f)
response = requests.post('http://url_for_working/, data=data)
response.text #There I have an Error about which I will say later
Run Code Online (Sandbox Code Playgroud)
oAuth2运作良好。但是在服务器端,request.data中没有任何产品
<QueryDict: {u'token_type': [u'type_is_ok'], u'access_token': [u'token_is_ok'],
u'expires_in': [u'36000'], u'coordinate_y': [u'8.4'],
u'coordinate_x': [u'12.3'], u'products': [u'count', u'id', u'count',
u'id'], u'address': [u'\u041c, 12'], …Run Code Online (Sandbox Code Playgroud) 我一直在尝试使用网站 Idealista ( https://www.idealista.com/ )的 API来检索房地产数据的信息。
由于我不熟悉 OAuth2,因此到目前为止我无法获得令牌。我刚刚获得了 api 密钥、秘密和一些关于如何挂载 http 请求的基本信息。
我会很感激这个 API 的功能的一个例子(最好是在 Python 中),或者一些关于处理 OAuth2 和 Python 的更通用的信息。