How to control direct url access? - spring

How to control direct url access in jsf 2.0, struts 2 and spring 3 ? I mean not login user type url and display always home or login page.

You can either use a project like spring-security to integrate with your application, or write your own servlet-filter
The stackoverflow servlet-filter tag has a good overview of servlet filters. For most servlet compatible web frameworks you can integrate a filter to intercept requests and redirect invalid or unauthorized requests to where they belong.

I suggest you to use Apache Shiro filter for control direct access for a certain url.
Look at the Apache Shiro configuration ini file where are the control of url access shown.
[main]
logout = org.apache.shiro.web.filter.authc.LogoutFilter
roles = org.apache.shiro.web.filter.authz.RolesAuthorizationFilter
authc.loginUrl=/faces/login.xhtml
authc.successUrl=/faces/index.xhtml
roles.unauthorizedUrl = /faces/unauthorized.xhtml
logout.redirectUrl = /faces/login.xhtml?status=loggedOut
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.authenticationQuery = SELECT PASSWORD FROM USERS WHERE USERS.USERNAME = ?
jdbcRealm.userRolesQuery = SELECT ROLE_NAME FROM ROLES, USER_ROLE, USERS WHERE ROLES.ROLE_ID = USER_ROLE.ROLE_ID AND USERS.USR_ID = USER_ROLE.USR_ID AND USERS.USERNAME = ?
jdbcRealm.permissionsQuery = SELECT PERMISSIONS.PERM_NAME FROM ROLES, PERMISSIONS_ROLE, PERMISSIONS WHERE ROLES.ROLE_ID = PERMISSIONS_ROLE.ROLE_ID AND PERMISSIONS.PERM_ID = PERMISSIONS_ROLE.PERM_ID AND ROLES.ROLE_NAME = ?
ds = com.mysql.jdbc.jdbc2.optional.MysqlDataSource
ds.user = maqraa
ds.password = maqraa
ds.databaseName = maqraa
ds.serverName = localhost
ds.portNumber = 3306
jdbcRealm.dataSource = $ds
securityManager.realms = $jdbcRealm
[urls]
/faces/login.xhtml = authc
/faces/admin/** = authc, roles[admin]
/faces/teacher/** = authc, roles[teacher]
/faces/reports/** = authc, roles[admin]
/faces/officer/** = authc, roles[officer]
/faces/manager/** = authc, roles[manager]
/faces/roles/** = authc, roles[admin]
Looking at the previous url(s) you will find out that any access for /faces/login.xhtml must be done by authenticated user in addition to access some of url(s) you must be a playing for a specific role(s).
Review Shiro tag on stackoverflow or see the Apache Shiro site.
I hope that help you.
Thanks.

Related

Grails Spring Security REST + LDAP

I am trying to set up Spring Security in Grails authenticating with a token (via the Spring Security REST plugin) and authorizing against LDAP. I have found several examples (I have about 20 browser tabs open right now), but none of them answer the whole question. Most of the examples are Grails + REST Security or Grails + LDAP Security, but no examples of Grails + REST + LDAP.
My issue is that the application tries to look in the database for users and roles, when I need it to look to LDAP.
I found the solution was to go into resources.groovy and configure the userDetailsService bean to use LDAP instead.The only "prerequisite" is that you must already have correct LDAP configurations to your LDAP server. I found this solution here: http://swordsystems.com/2011/12/21/spring-security-cas-ldap/. And only took the following piece.
// Place your Spring DSL code here
import grails.plugin.springsecurity.SpringSecurityUtils
beans = {
def config = SpringSecurityUtils.securityConfig
if (config.ldap.context.server) {
SpringSecurityUtils.loadSecondaryConfig 'DefaultLdapSecurityConfig'
config = SpringSecurityUtils.securityConfig
initialDirContextFactory(org.springframework.security.ldap.DefaultSpringSecurityContextSource,
config.ldap.context.server){
userDn = config.ldap.context.managerDn
password = config.ldap.context.managerPassword
}
ldapUserSearch(org.springframework.security.ldap.search.FilterBasedLdapUserSearch,
config.ldap.search.base,
config.ldap.search.filter,
initialDirContextFactory){
}
ldapAuthoritiesPopulator(org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator,
initialDirContextFactory,
config.ldap.authorities.groupSearchBase){
groupRoleAttribute = config.ldap.authorities.groupRoleAttribute
groupSearchFilter = config.ldap.authorities.groupSearchFilter
searchSubtree = config.ldap.authorities.searchSubtree
rolePrefix = "ROLE_"
convertToUpperCase = config.ldap.mapper.convertToUpperCase
ignorePartialResultException = config.ldap.authorities.ignorePartialResultException
}
userDetailsService(org.springframework.security.ldap.userdetails.LdapUserDetailsService,
ldapUserSearch,
ldapAuthoritiesPopulator){
}
}
}

Migration of Google Apps Marketplace app to oAuth 2.0 with additional scopes

We have app using oauth 1.0 in old marketplace. We are in process of migrating to oauth 2.0 for new marketplace. We are using UpgradeableApp API to do migration for existing domains. I am following steps specified here : https://developers.google.com/apps-marketplace/v1migratev2
As mentioned in the prerequisites in the above link: The scopes for the new and old apps must be compatible. But our new app has some additional scopes. Is there any way to grant access to these additional scopes while doing migration.
Only domain's admin or users can approve additional scopes.
Domain's admin receives an email notification after upgrade.
In your oauth2.0 app you can detect if all scopes have been approved or not. If not, you can show the user appropriate message to contact domain admin to get scopes approved.
For this we should have same scope in both old as well as on new listing. I am also facing the same problem of migrating the old users to new one. Kindly check the below code how I am migrating from old to new Users but every time I am getting 401 UnAuthorized, May I know what I am missing for this.
String url = String.Format("https://www.googleapis.com/appsmarket/v2/upgradableApp/{0}/{1}/{2}", oldAppId, chromeListing, domain);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "PUT";
request.ContentType = "application/json";
request.Accept = "application/json";
request.ProtocolVersion = HttpVersion.Version11;
request.Credentials = CredentialCache.DefaultCredentials;
request.Headers.Add("Authorization", "OAuth");
Hashtable postObj = new Hashtable();
postObj["Consumer Key"] = oldClientId;
postObj["Consumer Key Secret"] = oldSecret;
String s1 = new JavaScriptSerializer().Serialize(postObj);
var bs = Encoding.UTF8.GetBytes(s1);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
using (var sr = new StreamReader(response.GetResponseStream()))
{
result = sr.ReadToEnd();
sr.Close();
}
}

Grails Spring LDAP Security multiple domain use case

I have several DC in my LDAP(like DC=Ny, DC=Oh) and would like to authenticate the user from LDAP through grails spring ldap plugin.
Initially I have used following parameters in the config.groovy file and was able to authenticate the users from newyork but now I have to authenticate the users from both newyork and Ohio.
// Added by the Spring Security Core plugin:
grails.plugins.springsecurity.userLookup.userDomainClassName = 'com.test.SecUser'
grails.plugins.springsecurity.userLookup.authorityJoinClassName = 'com.test.SecUserSecRole'
grails.plugins.springsecurity.authority.className = 'com.test.SecRole'
// LDAP config
grails.plugins.springsecurity.ldap.context.managerDn = 'CN=P8,OU=P8,OU=Weblogic,OU=PR,OU=Groups - Application,DC=NY,DC=GWL,DC=com'
grails.plugins.springsecurity.ldap.context.managerPassword = 'test'
grails.plugins.springsecurity.ldap.context.server = 'ldap://NY.GWL.com:389/'
grails.plugins.springsecurity.ldap.authorities.ignorePartialResultException = true // typically needed for Active Directory
grails.plugins.springsecurity.ldap.search.base = 'DC=NY,DC=GWL,DC=com'
grails.plugins.springsecurity.ldap.search.filter="sAMAccountName={0}" // for Active Directory you need this
grails.plugins.springsecurity.ldap.search.searchSubtree = true
grails.plugins.springsecurity.ldap.auth.hideUserNotFoundExceptions = false
grails.plugins.springsecurity.ldap.search.attributesToReturn = ['mail', 'displayName'] // extra attributes you want returned; see below for custom classes that access this data
grails.plugins.springsecurity.providerNames = ['ldapAuthProvider', 'anonymousAuthenticationProvider'] // specify this when you want to skip attempting to load from db and only use LDAP
What kind of changes needs to be done in groovy.config file or does I need to do any code changes.
Any help on this will be really helpful.
Thanks

Get User Profile Picture Without Credentials, Possible?

Working on an email client.
Does anyone know if it is possible to get the profile pic of a user from the email and server URL without their password?
I'm working with Exchange 2013. I tried the HTTP POST option provided. It works like a charm but requires a log in.
Have a look at Exchange Impersonation.
You can have a specific user account impersonate another user account and access their details without the need for their username and password.
string impName = #"impy";
string impPassword = #"password";
string impDomain = #"domain";
string impEmail = #"impy#domain.com";
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
service.Credentials = new NetworkCredential(impName, impPassword, impDomain);
service.AutodiscoverUrl(impEmail);
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, #"user#domain.com");
More references:
http://msdn.microsoft.com/en-us/library/dd633680(v=exchg.80).aspx
you can use like this..
var userpicUrl = "/_layouts/15/userphoto.aspx?accountname=" + user.UserName + "&size=M&url=" + user.ProfilePictureURl;

Binding container managed authentication alias with DataSource using jython script

I'm using WebSphere 8.5
I've found out how to create JAASAuthData with username and password using jython script:
objServerAttrs = AdminControl.completeObjectName('WebSphere:type=Server,*')
cellName = AdminControl.getAttribute(objServerAttrs, 'cellName')
sec = AdminConfig.getid('/Cell:%s/Security:/' % cellName)
jaasAttr = [['alias', jaasAlias],['userId', jaasUser],['password', jaasPass]]
jaasAuthData = AdminConfig.create('JAASAuthData', sec, jaasAttr)
and how to create dataSource:
dsAttrs = [['name', 'myDS1'], ['jndiName','jdbc/MY/DS1']]
newDs = AdminConfig.create('DataSource', provider, dsAttrs)
Now I need to bind that JAASAuthData with my DataSource as 'Container-managed authentication alias', unfortunatelly I can't find anything in API, inspecting attributes of existing DataSources or any example for that task. How to create such binding?
You need to specify authDataAlias attribute:
dsAttrs = [['name', 'myDS1'], ['jndiName','jdbc/MY/DS1'], ['authDataAlias',jaasAlias]]
newDs = AdminConfig.create('DataSource', provider, dsAttrs)
The recommended way of configuring container-managed authentication alias is to set it on a resource reference during your application deployment.
It is still allowed (although deprecated) to configure it on DataSource level:
newDs = AdminConfig.create('DataSource', provider, dsAttrs)
mapping = AdminConfig.showAttribute(newDs, 'mapping')
AdminConfig.modify(mapping, [['mappingConfigAlias', jaasAlias], ['authDataAlias', jaasAlias]])
BTW: Your script would be more maintainable if you used WDR library http://wdr.github.io/WDR/ (I'm one of the main contributors).
jaasAlias = 'TheAuthAliasName'
provider = getid1('/JDBCProvider:TheProviderName/')
security = getid1('/Cell:/Security:/')
security.assure('JAASAuthData', {'alias':jaasAlias}, userId = 'user', password = 'password')
ds = provider.assure('DataSource', {'name':'myDS1'}, jndiName = 'jdbc/MY/DS1')
# component-managed authentication:
ds.authDataAlias = jaasAlias
# ... and container-managed authentication:
ds.mapping.mappingConfigAlias = jaasAlias
ds.mapping.authDataAlias = jaasAlias
save()
sync()
The above script can be safely re-run without failure or duplicate objects.

Resources