我创建了一个Spring Boot应用程序,我有授权和资源服务器,这是我的主要类:
private void AuthorizeWP()
{
string requestURL = @"http://mywordpressurl.com/oauth1/request";
UriBuilder tokenRequestBuilder = new UriBuilder(requestURL);
var query = HttpUtility.ParseQueryString(tokenRequestBuilder.Query);
query["oauth_consumer_key"] = "myWordPressKey";
query["oauth_nonce"] = Guid.NewGuid().ToString("N");
query["oauth_signature_method"] = "HMAC-SHA1";
query["oauth_timestamp"] = (Math.Truncate((DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds)).ToString();
string signature = string.Format("{0}&{1}&{2}", "GET", Uri.EscapeDataString(requestURL), Uri.EscapeDataString(query.ToString()));
string oauth_Signature = "";
using (HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes("myWordPressSecret")))
{
byte[] hashPayLoad = hmac.ComputeHash(Encoding.ASCII.GetBytes(signature));
oauth_Signature = Convert.ToBase64String(hashPayLoad);
}
query["oauth_signature"] = oauth_Signature;
tokenRequestBuilder.Query = query.ToString();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(tokenRequestBuilder.ToString());
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
这是我的application.yml:
@SpringBootApplication
@EnableResourceServer
@EnableAuthorizationServer
public class OauthServerApplication {
public static void main(String[] args) {
SpringApplication.run(OauthServerApplication.class, args);
}
}
要生成访问令牌,我只执行此URL(POST):
security:
user:
name: guest
password: guest123
oauth2:
client:
client-id: trustedclient
client-secret: trustedclient123
authorized-grant-types: authorization_code,refresh_token,password
scope: openid
它返回:
http://trustedclient:trustedclient123@localhost:8080/oauth/token?username=guest&password=guest123&grant_type=password
现在我需要知道如何验证令牌是否正确,有任何帮助吗?
答案 0 :(得分:7)
您有多种可能性,您可以:
1)将令牌存储在TokenStore
中,并在资源服务器的授权服务器上打开安全的验证令牌点。
2)如果授权服务器和资源服务器可以共享DataSource,(在您的情况下,它很容易,因为两者都在同一个应用程序中)。它们都可以使用指向同一数据库的JdbcTokenStore
,资源服务器可以直接检查此令牌存储中令牌的有效性。请参阅本教程:Spring REST API + OAuth2 + AngularJS
3)您可以使用带有JwtTokenStore
和JwtAccessTokenConverter
的签名JWT令牌。请参阅本教程:Using JWT with Spring Security OAuth
这两个教程都基于以下github存储库:https://github.com/Baeldung/spring-security-oauth