Swagger Authentication using Annotation - swagger

I am trying to have a basic Auth in my swagger ui.I am using Swagger 2.0.5 as a maven library.Using SwaggerConfig class to create docket Api and other configuration.
`
public class SwaggerConfig {
/**
* Every Docket bean is picked up by the swagger-mvc framework - allowing for multiple
* swagger groups i.e. same code base multiple swagger resource listings.
*/
#Bean
public Docket api() {
AuthorizationScope[] authScopes = new AuthorizationScope[1];
authScopes[0] = new AuthorizationScopeBuilder()
.scope("")
.build();
SecurityReference securityReference = SecurityReference.builder()
.reference("basicAuth")
.scopes(authScopes)
.build();
ArrayList<SecurityReference> reference = new ArrayList<SecurityReference>(1);
reference.add(securityReference);
ArrayList<SecurityContext> securityContexts = new ArrayList<SecurityContext>(1);
securityContexts.add(SecurityContext.builder().securityReferences(reference).build());
ArrayList<SecurityScheme> auth = new ArrayList<SecurityScheme>(1);
auth.add(new BasicAuth("basicAuth"));
Documentation Doc = new DocumentationBuilder().basePath("/swagger-ui.html").build();
return new Docket(DocumentationType.SWAGGER_2)
.securitySchemes(auth)
.securityContexts(securityContexts)
.select()
.apis(RequestHandlerSelectors.basePackage("com.toyota.tme.consumerapi.rest"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
/* #Bean
public Docket customDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.regex("/v1/.*"))
.build();
}*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Consumer API")
.description("Azure based Consumer API.")
.contact("CarIT")
.build();
}
}`
My Issue is,I am using authorization annotatation in my rest service to enable Basic Auth.
#Api(value = "/ping", tags = "1.Ping", description = "API",authorizations = {#Authorization(value="basicAuth")})
#RestController
#RequestMapping("/api")
public class ping {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
#RequestMapping(path = "/ping", method = RequestMethod.GET,
produces = MediaType.TEXT_HTML_VALUE)
#ApiOperation(value = "Ping service", httpMethod = "GET", response = String.class,
produces = "text/html", notes = "ping service",authorizations = {#Authorization(value="basicAuth")})
#ApiResponses(value = {
#ApiResponse(code = 200, message = "Success", response = String.class),
#ApiResponse(code = 400, message = "Bad request"),
#ApiResponse(code = 401, message = "Unauthorized"),
#ApiResponse(code = 404, message = "Not Found"),
#ApiResponse(code = 409, message = "Conflict"),
#ApiResponse(code = 503, message = "Dependent System(s) are unavailable"),
#ApiResponse(code = 500, message = "Unknown server Error occurred")})
public ResponseEntity<String> ping() {
this.logger.info("springframework api :Ping Request received for ConsumerAPI");
return new ResponseEntity<>(ApplicationConstants.Ping, HttpStatus.OK);
}
}
But this code is not working.I am not able to see any authorization asked by Swagger.Please need a help in this

Same for me. Solved this by moving the value authorizations from Api to ApiOperation annotation. Not beautiful but working.

Related

Not receiving access_token in three-legged oauth 2.0 flow in asp.net mvc (Blackboard Learn)

I have to implement three-legged authentication in ASP.NET MVC. I have followed the steps according to the Blackboard documentation, especially the link https://community.blackboard.com/docs/DOC-3976-three-legged-oauth
I have received authorization code by calling the REST API /learn/api/public/v1/oauth2/authorizationcode.After that according to the documentation (I followed the documentation exactly but I don't know what am I have been missing ), I built a POST request to /learn/api/public/v1/oauth2/token to get access_token but I am unable to get access_token.
Instead, access_token, I have been receiving a BadRequest. This means I am making a mistake to build my second request but I am unable to fix the problem. I haven't found any code sample in .NET to implement three legged authentication for Blackboard Learn. Could you please help me to resolve the issue?
This is my code to call both APIs to receive access_token.
public class HomeController : Controller
{
public ActionResult Index()
{
// GET /learn/api/public/v1/oauth2/authorizationcode
Guid stateId = Guid.NewGuid();
string applicationKey = "Application key goes here";
string redirectUrl = string.Format("https://Blackboard Learn URL goes here/learn/api/public/v1/oauth2/authorizationcode" +
"?redirect_uri=https://localhost:44300/Home/OAuth2Response&response_type=code&client_id={0}&scope=read&state={1}",
applicationKey, stateId);
Response.Redirect(redirectUrl, true);
return View();
}
public async Task<bool> OAuth2Response(string code = null, string state = null, string error = null, string error_description = null)
{
bool success = true;
string json = string.Empty;
string urlCommand = string.Format("/learn/api/public/v1/oauth2/token?code={0}&redirect_url=https://localhost:44300/Home/OAuth2Response", code);
try
{
using (HttpClient client = new HttpClient())
{
var endpoint = new Uri("Blackboard Learn URL goes here" + urlCommand);
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("grant_type", "authorization_code"));
HttpContent body = new FormUrlEncodedContent(postData);
// POST /learn/api/public/v1/oauth2/token
using (HttpResponseMessage response = await client.PostAsync(endpoint, body)) // Problem is here
{
if (response.IsSuccessStatusCode)
{
json = await response.Content.ReadAsStringAsync();
}
else
{
success = false;
}
}
}
}
catch (Exception err)
{
//hopefully we never end up here, log this exception for forensics
success = false;
}
return success;
}
}
NOTE: I can successfully receive an access_token in Postman tool.
Finally, the below code works perfectly for 3 legged authentications in ASP.NET MVC.
public class HomeController : Controller
{
//https://blackboard.jiveon.com/docs/DOC-3976-three-legged-oauth
public ActionResult Index()
{
// GET /learn/api/public/v1/oauth2/authorizationcode
Guid stateId = Guid.NewGuid();
string applicationKey = "Application key goes here";
string redirectUrl = string.Format("Blackboard Learn URL goes here/learn/api/public/v1/oauth2/authorizationcode" +
"?redirect_uri=https://localhost:44300/Home/OAuth2Response&response_type=code&client_id={0}&scope=read&state={1}",
applicationKey, stateId);
Response.Redirect(redirectUrl, true);
return View();
}
public async Task<bool> OAuth2Response(string code = null, string state = null, string error = null, string error_description = null)
{
bool success = true;
string json = string.Empty;
string urlCommand = string.Format("/learn/api/public/v1/oauth2/token?code={0}&redirect_uri=https://localhost:44300/Home/OAuth2Response", code);
try
{
using (HttpClient client = new HttpClient())
{
var endpoint = new Uri("Blackboard Learn URL goes here" + urlCommand);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("client_id:client_secret")));
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("grant_type", "authorization_code"));
HttpContent body = new FormUrlEncodedContent(postData);
using (HttpResponseMessage response = await client.PostAsync(endpoint, body))
{
if (response.IsSuccessStatusCode)
{
json = await response.Content.ReadAsStringAsync();
dynamic oauth2Result = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
string access_token = oauth2Result.access_token;
string refresh_token = oauth2Result.refresh_token; }
else
{
success = false;
}
}
}
}
catch (Exception err) {
//hopefully we never end up here, log this exception for forensics
success = false;
}
return success;
}
}

Testing Dropwizard Resource's POST method

Hello I have the following resource class
#Path("/api")
#Api("My API")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public class MyResource {
public MyResource() {
// assign some values in teh constructor
}
#POST
#Timed
#UnitOfWork
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#ApiOperation(
value = "",
response = Response.class)
#ApiResponses(
value = {#ApiResponse(code = 405, message = "Method not allowed"), #ApiResponse(code = 400,
message = "some custom mesage")})
public Response createMyObject(MyObject o, #Context UriInfo uriInfo)
throws JsonProcessingException {
}
And I am trying to unit test it using this
#Test
public void testCreate() throws JsonProcessingException {
Entity<?> entity = Entity.entity(myObjInstance, MediaType.APPLICATION_JSON_TYPE);
final Response response = resources.target("/api").request().post(entity);
}
This gives me a 404, I have verified that the resource is correctly registered. Also the GET methods in this resource work as expected. What am I doing wrong?

swagger securityDefinition with Resteasy

I did configure swagger with an Application subclass and the beanConfig object, my securityDefinition must allow swagger ui to show de api_key field to allow authentication for all my services layer.
BeanConfig beanConfig = new BeanConfig();
beanConfig.setSchemes(new String[] { "http" });
beanConfig.setHost("192.168.4.9:8080");
beanConfig.setBasePath("/cjppa/rest");
beanConfig.setResourcePackage("com.cjppa.fpuna.backend.resources");
beanConfig.setScan(true);
beanConfig.setPrettyPrint(true);
io.swagger.models.Info info = new io.swagger.models.Info();
io.swagger.models.Contact contact = new io.swagger.models.Contact();
info.setVersion("1.0");
beanConfig.setInfo(info);
io.swagger.models.auth.ApiKeyAuthDefinition apikey = new
io.swagger.models.auth.ApiKeyAuthDefinition();
apikey.setName("x-token");
apikey.setIn(In.HEADER);
Swagger swagger = new Swagger().info(info);
swagger.securityDefinition("api_key", apikey);
beanConfig.configure(swagger);
the expected api_key comes in the "x-token" http header
I tried also to bring swagger into my resteasy webservice with using BasicAuthentification for some operations of my webservice. I imported swagger via maven in my pom.xml:
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-jaxrs</artifactId>
<version>1.5.18</version>
</dependency>
In my Application class I configured the BeanConfig:
import javax.ws.rs.ApplicationPath;
import io.swagger.jaxrs.config.BeanConfig;
#ApplicationPath("/rest")
public class Application extends javax.ws.rs.core.Application{
public Application() {
BeanConfig beanConfig = new BeanConfig();
beanConfig.setVersion("1.0");
beanConfig.setResourcePackage("de.mycompany.topic.ws");
beanConfig.setBasePath("/de.mycompany.topic.ws/rest/");
beanConfig.setScan(true);
}
}
The important thing is to configure the BasicAuthentification in an ReaderListener implementation via Annotations. basicAuth is an arbitrary name.
import io.swagger.annotations.BasicAuthDefinition;
import io.swagger.annotations.SecurityDefinition;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.jaxrs.Reader;
import io.swagger.jaxrs.config.ReaderListener;
import io.swagger.models.Swagger;
#SwaggerDefinition(securityDefinition = #SecurityDefinition(basicAuthDefinitions = {
#BasicAuthDefinition(key = "basicAuth")
}) )
public class SwaggerCustomizeDefinition implements ReaderListener {
#Override
public void beforeScan(Reader reader, Swagger swagger) {
}
#Override
public void afterScan(Reader reader, Swagger swagger) {
}
}
In MyRestService I annotate my operations that should be not usable without basic authentification. See here e.g. for saving customers:
#Api
#Path("/")
public class MyRestService {
private final static String UTF8 = ";charset=UTF-8";
#POST
#Path("/customer")
#Produces(MediaType.APPLICATION_JSON + UTF8)
#ApiOperation(
value = "Saves customer specified in the body",
notes = "note that appears in swagger ui",
authorizations = {
#Authorization(value = "basicAuth", scopes={})
})
#ApiResponses(value = {
#ApiResponse(code = 201, message = "customer created"),
#ApiResponse(code = 401, message = "Unauthorized"),
#ApiResponse(code = 404, message = "customer format not supported"),
})
public Response saveCustomer(
String content,
#BasicAuthDefinition(key = "basicAuth") #HeaderParam("Authorization") String authorization) {
// authorization
try {
if (!MyManager.isAuthorized(authorization)) {
return Response.status(Status.UNAUTHORIZED).build();
}
} catch (Exception e) {
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}
//do the work, authorization was ok
}
}
That's it. I tried a lot of variations and this was the only one that works for me in whole. My main problem was, that the authorize button not appears in the ui and the lock above the single methods in the swagger ui was not clickable so that the basic authentification modal dialog not appears. With this implementation it works.
you can implements io.swagger.jaxrs.config.ReaderListener ,addSecurity in afterScan method . eg:
#SwaggerDefinition(securityDefinition = #SecurityDefinition(apiKeyAuthDefinitions = {
#ApiKeyAuthDefinition(in = ApiKeyAuthDefinition.ApiKeyLocation.HEADER, key = "token", name = "E-token"),
#ApiKeyAuthDefinition(in = ApiKeyAuthDefinition.ApiKeyLocation.HEADER, key = "userId", name = "E-userId"),
#ApiKeyAuthDefinition(in = ApiKeyAuthDefinition.ApiKeyLocation.HEADER, key = "corpId", name = "E-corpId") }) )
public class SwaggerCustomizeDefinition implements ReaderListener {
#Override
public void beforeScan(Reader reader, Swagger swagger) {
}
#Override
public void afterScan(Reader reader, Swagger swagger) {
swagger.addSecurity(new SecurityRequirement().requirement("token"));
swagger.addSecurity(new SecurityRequirement().requirement("userId"));
swagger.addSecurity(new SecurityRequirement().requirement("corpId"));
}
}

Error processing your OAuth request: Invalid oauth_verifier parameter

I'm following https://dev.twitter.com/web/sign-in/implementing to implement OAuth signup in my application with twitter.
Here is the service which presents the User the authorize this app dialog from twitter:
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/twitter")
public Response redirectToTwitter() {
Configuration cfg = new ConfigurationBuilder().setOAuthConsumerKey(TWITTER_CONSUMER_KEY)
.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET)
.build();
Twitter twitter = new TwitterFactory(cfg).getInstance();
String callbackURL = "https://localhost:9090/app/ui/oauth/twitter";
try {
RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL);
String authURL = requestToken.getAuthenticationURL();
return Response.seeOther(URI.create(authURL)).build();
} catch (TwitterException e) {
LOG.error(e.getMessage(), e);
return ErrorResponse.create(e.getMessage());
}
}
This works and redirects the browser to the Twitter Page which asks for authorization. When I click Sign In the redirect dialog appears which redirect me to a URL something like:
https://localhost:9090/app/ui/oauth/twitter?oauth_token=6oWQxQAAAAAAgyORAAABTtmVVFM&oauth_verifier=GMX5SiqnkFfUu2MgirTDJnkJmtHZXn5H
#GET
#Path("/twitter")
public SocialSignInView login(#QueryParam("oauth_token") String token,
#QueryParam("oauth_verifier") String verifier) {
Configuration cfg = new ConfigurationBuilder().setOAuthConsumerKey(TWITTER_CONSUMER_KEY)
.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET)
.setOAuthAccessToken(token)
.build();
Twitter twitter = new TwitterFactory(cfg).getInstance();
String callbackURL = "https://localhost:9090/app/ui/oauth/twitter";
String screenName = null;
try {
RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL);
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
screenName = accessToken.getScreenName();
} catch (TwitterException e) {
LOG.error(e.getMessage(), e);
}
return new SocialSignInView(screenName);
}
At this point I have all the required parameters - according to https://dev.twitter.com/web/sign-in/implementing 3. - to retrieve an access token, however, I don't know how to put together a RequestToken object form the existing oauth_token.
With the code above I'm receiving the following error:
ERROR 13:33:06.478 [dw-165 - GET /app/ui/oauth/twitter?oauth_token=6oWQxQAAAAAAgyORAAABTtmVVFM&oauth_verifier=GMX5SiqnkFfUu2MgirTDJnkJmtHZXn5H] r.d.d.resources.SocialSignInCompleteResource: 401:Authentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
Error processing your OAuth request: Invalid oauth_verifier parameter
You need to set oauth_verifier in the header when you are requesting https://api.twitter.com/oauth/access_token.
These oauth_verifier you are getting as get parameters. So just set oauth_verifier=params[:oauth_verifier] in header.
I also had this problem with twitter4j.
I had been following the this tutorial (full code here).
However, the code wasn't brilliantly written, so I made a few changes and ended up breaking things which resulted in the "Error processing your OAuth request: Invalid oauth_verifier parameter" error.
Basically, the problem/solution lay with how I got the oauth request token from twitter4j.
Paying attention to the getRequestToken() method, this is the right way to implement it:
import android.util.Log;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
public final class TwitterUtil {
private final static String TAG = TwitterUtil.class.getSimpleName();
static TwitterUtil instance = new TwitterUtil();
public static TwitterUtil getInstance() {
return instance;
}
private TwitterFactory twitterFactory;
private Twitter twitter;
private RequestToken requestToken = null;
private TwitterUtil() {
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey(Constants.TWITTER_CONSUMER_KEY);
configurationBuilder.setOAuthConsumerSecret(Constants.TWITTER_CONSUMER_SECRET);
Configuration configuration = configurationBuilder.build();
twitterFactory = new TwitterFactory(configuration);
twitter = twitterFactory.getInstance();
}
TwitterFactory getTwitterFactory() {
return twitterFactory;
}
void setTwitterFactory(AccessToken accessToken) {
twitter = twitterFactory.getInstance(accessToken);
}
public Twitter getTwitter() {
return twitter;
}
RequestToken getRequestToken() {
if (requestToken == null) {
try {
requestToken = twitterFactory.getInstance().getOAuthRequestToken(Constants.TWITTER_CALLBACK_URL);
}
catch (TwitterException e) {
Log.e(TAG, "Could not get Twitter OAuth Request Token", e);
}
}
return requestToken;
}
public void reset() {
instance = new TwitterUtil();
}
}
And this is the wrong way to implement it:
public final class TwitterUtil_WRONG {
private final static String TAG = TwitterUtil_WRONG.class.getSimpleName();
static TwitterUtil_WRONG instance = new TwitterUtil_WRONG();
public static TwitterUtil_WRONG getInstance() {
return instance;
}
private TwitterFactory twitterFactory;
private Twitter twitter;
private TwitterUtil_WRONG() {
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey(Constants.TWITTER_CONSUMER_KEY);
configurationBuilder.setOAuthConsumerSecret(Constants.TWITTER_CONSUMER_SECRET);
Configuration configuration = configurationBuilder.build();
twitterFactory = new TwitterFactory(configuration);
twitter = twitterFactory.getInstance();
}
TwitterFactory getTwitterFactory() {
return twitterFactory;
}
void setTwitterFactory(AccessToken accessToken) {
twitter = twitterFactory.getInstance(accessToken);
}
public Twitter getTwitter()
{
return twitter;
}
RequestToken getRequestToken() {
try {
return twitterFactory.getInstance().getOAuthRequestToken(Constants.TWITTER_CALLBACK_URL);
}
catch (Exception e) {
Log.e(TAG, "Could not get Twitter OAuth Request Token", e);
return null;
}
}
public void reset() {
instance = new TwitterUtil_WRONG();
}
}
I had the same issue and fixed it by passing the oauth_verifier in the
twitter.getOAuthAccessToken() when requesting for the AccessToken.

Google OAuth 2 Error: redirect_uri_mismatch random url parameter ASP.NET

I've done authentication via VK, Instagram, Facebook in my site by template below.
However google requires "Redirect URL".
My redirect URL is like this:
http://localhost:4588/main/AuthenticationCallback?__provider__=google%2B&__sid__=6f3cc5957e4742758719f9b7decc2c09
Parameter "sid" is random every time. So I can't give google precise URL. I tried to input http://localhost:4588/main/AuthenticationCallback as I did for Instagram and it worked for Instagram but Google keeps showing me "400 Error: redirect_uri_mismatch"
I've also tried to pass http://localhost:4588/main/AuthenticationCallback as URL parameter in authorization url to google below. But in this case method "IAuthenticationClient.RequestAuthentication" is not called at all.
Can you advise me what should I input as "Redirect URL" for my Google app?
Template class working with OAuth2:
public class GoogleAuthenticationClient : IAuthenticationClient
{
public string appId;
public string appSecret;
private string redirectUri;
public GoogleAuthenticationClient(string appId, string appSecret)
{
this.appId = appId;
this.appSecret = appSecret;
}
string IAuthenticationClient.ProviderName
{
get { return "google+"; }
}
void IAuthenticationClient.RequestAuthentication(HttpContextBase context, Uri returnUrl)
{
var APP_ID = this.appId;
this.redirectUri = context.Server.UrlEncode(returnUrl.ToString());
var address = String.Format(
"https://accounts.google.com/o/oauth2/auth?client_id={0}&redirect_uri={1}&response_type=code&scope={2}",
APP_ID, this.redirectUri, "https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email"
);
HttpContext.Current.Response.Redirect(address, false);
}
class AccessToken
{
public string access_token = null;
public string user_id = null;
}
class UserData
{
public string uid = null;
public string first_name = null;
public string last_name = null;
public string photo_50 = null;
}
class UsersData
{
public UserData[] response = null;
}
AuthenticationResult IAuthenticationClient.VerifyAuthentication(HttpContextBase context)
{
try
{
string code = context.Request["code"];
var address = String.Format(
"https://accounts.google.com/o/oauth2/token?client_id={0}&client_secret={1}&code={2}&redirect_uri={3}",
this.appId, this.appSecret, code, this.redirectUri);
var response = GoogleAuthenticationClient.Load(address);
var accessToken = GoogleAuthenticationClient.DeserializeJson<AccessToken>(response);
address = String.Format(
"https://www.googleapis.com/plus/v1/people/{0}?access_token=1/fFBGRNJru1FQd44AzqT3Zg",
accessToken.user_id);
response = GoogleAuthenticationClient.Load(address);
var usersData = GoogleAuthenticationClient.DeserializeJson<UsersData>(response);
var userData = usersData.response.First();
return new AuthenticationResult(
true, (this as IAuthenticationClient).ProviderName, accessToken.user_id,
userData.first_name + " " + userData.last_name,
new Dictionary<string, string>());
}
catch (Exception ex)
{
return new AuthenticationResult(ex);
}
}
public static string Load(string address)
{
var request = WebRequest.Create(address) as HttpWebRequest;
using (var response = request.GetResponse() as HttpWebResponse)
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
}
public static T DeserializeJson<T>(string input)
{
var serializer = new JavaScriptSerializer();
return serializer.Deserialize<T>(input);
}
}
Code in my Controller:
public void ExternalLogin(string provider)
{
OAuthWebSecurity.RegisterClient(
client: new GoogleAuthenticationClient(
"APP_ID", "APP_CODE"),
displayName: "google+", // надпись на кнопке
extraData: null);
ExternalLoginCallback(provider);
}
public void ExternalLoginCallback(string provider)
{
OAuthWebSecurity.RequestAuthentication(provider, Url.Action("AuthenticationCallback"));
}
public ActionResult AuthenticationCallback()
{
var result = OAuthWebSecurity.VerifyAuthentication();
if (result.IsSuccessful == false)
{
return null;
}
else
{
var provider = result.Provider;
var uniqueUserID = result.ProviderUserId;
return RedirectToAction("Main", "Main");
}
}
You can authorise a redirect URI as explained below, but you can't add any parameters to the redirect uri, please see this answer on how the parameters can be passed to Google google oauth2 redirect_uri with several parameters
The authorised redirect URI needs to be set when you created your client ("APP_ID", "APP_CODE") on the Google Cloud Console. Simply navigate to the API console for your project and edit the Web client to set the correct redirect URI you would like to use.

Resources