OAuth2.0 Support In Liferay JSON Web Services - oauth

I have created two API through service builder as given below
public class PrescriptionServiceImpl extends PrescriptionServiceBaseImpl {
#AccessControlled(guestAccessEnabled = true)
public String freeService(){
return "free service";
}
public String privateService(){
return "private service";
}
}
I want to authenticate the second service with OAuth 2.0 since the first service is already on guest mode. Does Liferay 6.2 support OAuth 2.0 token based authentication apart from Basic Authentication? If so please help me how to proceed further.
These are the HTTP URL created by Liferay for above two services
http://localhost:8080/api/jsonws/Prescription-portlet.prescription/free-service
http://localhost:8080/api/jsonws/Prescription-portlet.prescription/private-service

Liferay 6.x does not support OAuth 2 for /api/jsonws service access.
You would need to implement your own AuthVerifier implementation for OAuth 2 and add it to the list declared in portal-ext.properties.

Related

OAuth and OWIN Authentication - Confusion

I have been asked to create a 'Authentication/Authorization' Middle man or broker as an http,MVC web application, so that this can be used to multiple applications on our organization for authentication/Authorization purposes. Means, users will signup, Login on this broker application and once confirmed Authenticated, authorized user, he will get redirected to client applications accordingly. This is the use case.
I am choosing OAuth and OWIN to develop this broker in an MVC applicaiton, which means OAuth(Authorization) will issue access token + refresh token, once user is successfully authenticated. I use normal, simple, minimal authentication logic inside the Oauth Authorization Server's Login Controller as below :
public class AccountController : Controller
{
public ActionResult Login()
{
var authentication = HttpContext.GetOwinContext().Authentication;
if (Request.HttpMethod == "POST")
{
var isPersistent = !string.IsNullOrEmpty(Request.Form.Get("isPersistent"));
if (!string.IsNullOrEmpty(Request.Form.Get("submit.Signin")))
{
var user = Constants.Users.UserCollection.Where(u => u.Email.ToLower() == Request.Form["username"].ToLower().Trim() && u.Password == Request.Form["password"].Trim());
if (user.Count() > 0)
{
authentication.SignIn(
new AuthenticationProperties { IsPersistent = isPersistent },
new ClaimsIdentity(new[]
{ new Claim(ClaimsIdentity.DefaultNameClaimType, Request.Form["username"]),
new Claim("DisplayName", user.FirstOrDefault().DisplayName) } , "Application"));
}
}
}
return View();
}
This is the MSFT sample application I am following to develop this conceptual application.
https://learn.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server.
My question here is : I read in many articles like, its not good to use Oauth authentication, else use OPENID Connect handling authentication. To be frank, I am not used with OPENID Connect and I am not sure about the necessity of creating a OPENID Provider for my organization, Since this service will be used only by customers of our organization - less than 200,000 users. We hardly need a user signup and login, this account need to be used among different web applications of our organization. Please help me here with your inputs. Thanks in advance.
I think your question is about the benefits of OpenID Connect (OIDC) over OAuth 2.0.
OIDC builds upon OAuth 2.0 so you can use all of it's features. In a practical context, the question you should ask yourself is: Do other applications (clients, APIs), which use your "broker" (authorization server/security token service/OpenID provider) need to know something about the user, who just logged in? Do they need the ID, it's roles, username etc..? If the answer is no and you just need a signed token you are probably better of with OAuth.
If you start to include user claims (=attributes) in your access token you should at least have a look at OIDC. Also note, that even if you include claims in your access token, these are meant for the resource server (=API) and are normaly inaccessable for the client (unless you extract them and expose them on the API side - this is basically what the OIDC userinfo endpoint does).

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.

Passing display=touch to Facebook OAuth with Microsoft OWIN

I have an ASP.NET MVC5 app which I have configured for Facebook OAuth 2 login using the ASP.NET OWIN authentication model that ships with this version of MVC.
I want to tell Facebook to optimize its login page for touch-based devices. Facebook documentation says I should be able to do this by adding a display=touch parameter to the query string we pass to Facebook when we kick off the OAuth flow. (see https://developers.facebook.com/docs/reference/dialogs/oauth/)
This ought to be a simple thing to do, but I am at a total loss about how to go about customizing the various OWIN middleware classes to add this parameter.
How do I customize the OWIN auth flow to modify the Facebook OAuth URL?
Basically: you need to go ahead and create an authentication provider for Facebook. So create a class that inherits from FacebookAuthenticationProvider. Within this class, override the "ApplyRedirect" method. Make it look something like:
public override void ApplyRedirect(FacebookApplyRedirectContext context)
{
context.Response.Redirect(context.RedirectUri + "&display=popup");
}
Now simply wire this class up with your configuration, like so:
app.UseFacebookAuthentication(new FacebookAuthenticationOptions
{
Provider = new **<the name of the class that you created>**()
// the rest of your configuration such as app ID and secret
});
And that should be it!
Answer courtesy of #nlaq here: Facebook PopUp Login with Owin

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 develop user-authenticated REST service with Azure ACS

I'm developing a REST service that uses MS Azure Access Control Service for authentication. If the examples are any indication, the typical way to secure a REST service this way would be to provide a global username and pw, private key, or X.509 cert for the protected service. However, I want to use the passive user login mechanism on a mobile device with a flow more like the following:
Unauthenticated user attempts to access protected service from app
Mobile app redirects to browser app (or embedded browser)
User selects identity provider to use for login (facebook, google, etc.) from ACS login page
User enters credentials for identity provider
Browser redirects back to app
App somehow gets the SWT token to use with subsequent REST requests.
I'm stuck at about step 5--getting the SWT token, and the existing examples I've found don't seem to address this scenario. In addition, I'm actually trying to build a proof of concept with a desktop client in WPF, which may complicate things. Can anyone suggest a specific tutorial or a path to pursue that uses the per-user authentication vs. per-service? Thanks.
EDIT:
As I'm digging into this deeper, I've realized that the examples posted below (and most others) are based on OAuth WRAP, which has been deprecated in favor of OAuth 2.0. Can anyone suggest a more up to date reference? Googling has turned up http://blogs.msdn.com/b/adventurousidentity/archive/2011/09/18/acs-v2-oauth-2-0-delegation-support-explained.aspx and http://connect.microsoft.com/site1168/Downloads/DownloadDetails.aspx?DownloadID=32719 but they're not the most intuitive.
You should look into the ACS Windows Phone sample:
http://msdn.microsoft.com/en-us/library/gg983271.aspx
Here instead of using Silverlight you will be using WPF. Most of the code should be re-usable. Note that since you are using WPF you will need to register your own object for scripting e.g:
[ComVisibleAttribute(true)]
public class NotifyHandler
{
public void Notify(string notifyString)
{
// Here I have the token.
}
}
this.webBrowser1.ObjectForScripting = new NotifyHandler();
Update:
The sample above uses OAuth Wrap to contact the secured service. If you would like to use OAuth2 you should change the way the "Authorization" header set:
OAuth WRAP case:
WebClient client = new WebClient();
client.Headers["Authorization"] = "OAuth " + _rstrStore.SecurityToken;
OAuth2 case:
WebClient client = new WebClient();
client.Headers["Authorization"] = string.Format("OAuth2 access_token=\"{0}\"", token);
You can use the "Simple Service" sample as a guide to implement your token validation in your REST service:
http://msdn.microsoft.com/en-us/library/gg185911.aspx
Yet if you would like to implement a more complete sample you can look at how CustomerInformationService is protected in the CTP version 1.4:
https://connect.microsoft.com/site1168/Downloads/DownloadDetails.aspx?DownloadID=35417
Take a look at this one:
WPF Application With Live ID, Facebook, Google, Yahoo!, Open ID
http://social.technet.microsoft.com/wiki/contents/articles/4656.aspx

Resources