BOT framework External client authentication - oauth-2.0

I launch the client web application from the BOT framework to process the thrid party authentication. The client application process the the third party authentication using OAuth and Owin. Is there any way to send the useridentity back to the BOT framework?
and able to get the access token from the client browser. But the same api call is not working from the BOT framework or from other client. (Ex: Httpget (clientappurl/api/GetToken)
Any ideas?
//api/GetToken ---GET
public string GetToken()
{
var identity = new ClaimsIdentity (User.Identity.AuthenticateType)
identity.AddClaim ("sub", User.Identity.GetUserName()))
AuthenticationTicket ticket = new AuthenticationTicket (identity,
AuthenticationProperties());
string token = Startup. OAuthOptions.AccessTokenFormat.Protect(ticket);
return token;
}

I think what you are looking for is called the backchannel. There is an example in this link that may be all you need. There is also another example here https://github.com/Microsoft/BotFramework-WebChat/blob/master/samples/backchannel/index.html. The backchannel will allow you to communicate between the client and the bot.

Related

Broken AntiforgeryToken with Microsoft MSAL

I'm working with ASP.Net MVC and I have a problem using MSAL while authenticating a User. This is because, as we use AntiforgeryToken, when the user sign in in the page of Microsoft, the token breaks and we get an error related to the token.
My question is, is there a way to keep the token even after being redirected from Microsoft login page? Or can I recreate it?
I've search on other questions and google and found nothing.
Thank you.
Yes you can save the token in your application like this:
[AuthorizeForScopes(Scopes = new[] { "user.read" })]
public async Task<IActionResult> Profile()
{
// Acquire the access token.
string[] scopes = new string[]{"user.read"};
string accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(scopes);
context.Token = accessToken;
}
Alternatively, you can explicitly acquire tokens by using the acquire-token methods as described in the core MSAL library. The MSAL wrapper provides the HTTP interceptor, which will automatically acquire access tokens silently and attach them to the HTTP requests to APIs.

Authenticate to Dynamics 365 On premise

I am trying connect to Dynamics 365 On-premise with the OData client for .net
I tried to authenticate through basic authentication, however this is not working.
var c = new Microsoft.Dynamics.CRM.System(new Uri("https://mycrm01/crm/api/data/v8.2/"));
c.SendingRequest2 += (o, requestEventArgs) => {
var creds = username + ":" + password;
var encodedCreds = Convert.ToBase64String(Encoding.ASCII.GetBytes(creds));
requestEventArgs.RequestMessage.SetHeader("Authentication", "Basic" + encodedCreds);
};
var contacts = c.Contacts.Where(x => x.Firstname=="testuser");
foreach (var contact in contacts)
{
}
The error I recieve is: HTTP Error 401 - Unauthorized: Access is denied
Can someone help me how this is done?
In general I only use the OData client from JavaScript. When using .NET, I use the SDK libraries that provide authentication and access via the CrmServiceClient class.
To use the OData client from C#, this article outlines the various authentication methods: https://msdn.microsoft.com/en-us/library/mt595798.aspx
Web API authentication patterns
There are three different ways to manage authentication when using the
Web API. With JavaScript in web resources
When you use the Web API with JavaScript within HTML web resources,
form scripts, or ribbon commands you don’t need to include any code
for authentication. In each of these cases the user is already
authenticated by the application and authentication is managed by the
application. With on-premises deployments
When you use the Web API for on-premises deployments you must include
the user’s network credentials. The following example is a C# function
that will return an HttpClient configured for a given user’s network
credentials: C#
private HttpClient getNewHttpClient(string userName,string
password,string domainName, string webAPIBaseAddress) {
HttpClient client = new HttpClient(new HttpClientHandler() { Credentials = new NetworkCredential(userName, password, domainName)
});
client.BaseAddress = new Uri(webAPIBaseAddress);
client.Timeout = new TimeSpan(0, 2, 0);
return client;
}
With Microsoft Dynamics 365 (online) or internet facing deployments
When you use the Web API for Dynamics 365 (online) or an on-premises
Internet-facing deployment (IFD) you must use OAuth as described in
Connect to Microsoft Dynamics 365 web services using OAuth.
If you’re creating a single page application (SPA) using JavaScript
you can use the adal.js library as described in Use OAuth with
Cross-Origin Resource Sharing to connect a Single Page Application to
Microsoft Dynamics 365.

ASP.NET Core API Facebook registration/login

I'm working on ASP.NET Core API and need to add option to register with social service, e.g. Facebook.
Scenario should be e.g. Android App user should click "Sign up with Facebook" at startup, then Facebook app should open then user should click confirm and be registered in app.
Default Asp.net web example shows how to do it with web page on same host as APIs with return Challenge() response that basically returns HTML page as I understood.
What is the correct flow here and is there any existing libraries to do that?
As I understand now flow is something like this:
1. API server has my AppId and AppSecret from Facebook
2. Android app should request "applciation token" from API server
3. Android app should call Facebook with that token and get "user confirmation token"
4. Android app should pass "user confirmation token" to API server
5. API server should call Facebook with "AppId/AppSecret token + user confrimation token" and get details about user and create local user in database.
6. API server should create "API token" for that user
7. Android app should use "API token"
So at least I want to understand what to replace this code from example with:
public IActionResult ExternalLogin(string provider, string returnUrl = null) {
// Request a redirect to the external login provider.
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
var properties = signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return Challenge(properties, provider);
the thing to understand is the default web app template provided in VS 2015 uses ASP.NET Identity with cookie authentication. cookie auth works for web browsers but for an android app to authenticate you would need something to issue jwt tokens in addition to or instead of cookies. There is nothing built in provided by Microsoft for that in asp.net core, the recommendation is to use IdentityServer4

ASPNet Identity Authentication MVC5 Client web site->Auth Server-> Web API server

I'm a newbie for ASPnet identity services and we require a following requirement.
Following is the architecture setup
1. Appserver
Appsever having
a. Entity Framework
b. ASP.Net Web API2 Odata services
c. Authorization server
2. Webserver
ASP.Net MVC 5 application (Client which access the App server)
The flow needs to be
MVC5 Cleint application having a login / Register form
While register / login the information needs to send to the authorization server int he app server, Authorize and creating the claims using Identity Services.
Once the Identity has been created in the Authorization server, the client application should logged in
I'm aware of getting bearer token from authentication server and that will be used as header information to access the API service
All we are lacking is the MVC client application should use the same identity claims that have created in the Authorization server.
Is there any way to access the claims which are created in the auth server.
I have got some samples about how to authenticate in the auth server and receiving token though OWIN and from this token we can access the API securely but I need of the client web application needs to sign in based on the token
I have gone through the following links
http://blogs.msdn.com/b/webdev/archive/2013/09/20/understanding-security-features-in-spa-template.aspx
Also, I require to add claims when ever it requires after login as well
I have resolve this issue as follows, but I'm not sure this is the effective method
Once log-in and retrieve the bearer token (this token should assigned with claims identity already such as username, role .. etc)
In the web api AccountController, need to create a method to retrieve the default claims which requires for client web application. Please check the follows
[Authorize]
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
[Route("UserInfo")]
public UserInfoViewModel GetUserInfo()
{
var firstname = ((ClaimsIdentity)User.Identity).Claims.Where(c => c.Type.Equals("FirstName")).SingleOrDefault();
var lastname = ((ClaimsIdentity)User.Identity).Claims.Where(c => c.Type.Equals("LastName")).SingleOrDefault();
var IsApproved = ((ClaimsIdentity)User.Identity).Claims.Where(c => c.Type.Equals("IsApproved")).SingleOrDefault();
var userinfo = new UserInfoViewModel
{
UserName = User.Identity.GetUserName(),
FirstName = firstname.Value.ToString(),
LastName = lastname.Value.ToString(),
UserApproved = Convert.ToBoolean(IsApproved.Value.ToString()),
HasRegistered = externalLogin == null,
LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null
};
return userinfo;
}
From the client, this actin will be called through the token as a header.
Once we have got the information (is in Json string format) needs to serialize with the UserInfoViewModel class (user defined viewmodel is based on the info we require and send from webapi account) with javascript serializer
Using these viewmodel information, assign them to local storage and using (cookies for my case) as a identity at local
keep logout webapi too when ever you logs out from web app.
Please let me know if you need more info or code

How to build secured api using ServiceStack as resource server with OAuth2.0?

I have build a OAuth2.0 Authorization server using dotnetopenauth that will manage authentication, authorization, and assign accessToken to the caller. The caller will use the access token to access the api (webservices) at resource server.
If follow the sample provided by dotnetopenauth in Resource Server, api that builded using WCF can be authenticated by OAuthAuthorizationManager
If using ServiceStack to build my api in Resource Server, how to build the authentication process that verify the incoming api request based on assigned OAuth2.0 access token? The functionality should similar to OAuthAuthorizationManager in the dotnetopenid sample and not based on login session.
Just some update
I didn't use the AuthenticateAttribute or RequiredRoleAttribute from ServiceStack.ServiceInterface.
I create 2 custom RequestFilterAttribute to replace the functions provided by AuthenticateAttribute and RequiredRoleAttribute.
In each custom RequestFilterAttribute's Execute method, I'm using method in dotnetopenauth to verify the access token.
//httpReq==req from Execute(IHttpRequest req, IHttpResponse res, object requestDto)
The code for the access token verification as following, reference the relevant documentation from both servicestack and dotnetopenauth for more info. ResourceServer is class from dotnetopenauth
HttpRequestBase reqBase = new HttpRequestWrapper((System.Web.HttpRequest)httpReq.OriginalRequest);
var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(AuthorizationServerPublicKey, ResourceServerPrivateKey));
IPrincipal ip = null;
resourceServer.VerifyAccess(reqBase, out ip);
If the ip is null then not authenticated, if not null, the incoming request is valid and can use the ip to check the role e.g. ip.IsInRole(requiredRole)
I'm not sure this is the correct way to do the checking or not, but it's works for me. Any better solution are welcome.

Resources