I've been studying the Google authentication API (AuthSub)... My question is, how do I get the user's account information (at least their Gmail address) after the authentication has passed?
Because currently, all I get back from the authentication process is a token granting me access to which ever Google service I have specified in the scope, but there's no easy way to even get the user's login id (Gmail address) as far as I can tell...
If so, what Google service allows me to access the user's information?
Google Authentication API is a token based system to authenticate a valid user. It does not expose any of other interface that allows to get account holder information back to authorizer.
Using the Google AppEngine GData services, you can request the user to give you access to their Google Mail, Calendar, Picasa, etc. Check it out here.
You can get some of the data through the OpenID API, with the ax extension. If you are authenticating with other methods, best I found is calling https://www-opensocial.googleusercontent.com/api/people/#me/#self and it will get you name, email and picture. Be sure to have http://www-opensocial.googleusercontent.com/api in scopes when authenticating.
[ValidateInput(false)]
public ActionResult Authenticate(string returnUrl)
{
try
{
logger.Info("" + returnUrl + "] LoginController : Authenticate method start ");
var response = openid.GetResponse();
if (response == null)
{
try
{
string discoveryuri = "https://www.google.com/accounts/o8/id";
//OpenIdRelyingParty openid = new OpenIdRelyingParty();
var fetch = new FetchRequest();// new
var b = new UriBuilder(Request.Url) { Query = "" };
var req = openid.CreateRequest(discoveryuri, b.Uri, b.Uri);
fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
fetch.Attributes.AddRequired(WellKnownAttributes.Name.FullName);
req.AddExtension(fetch);
return req.RedirectingResponse.AsActionResult();
}
catch (ProtocolException ex)
{
logger.ErrorFormat(" LoginController : Authenticate method has error, Exception:" + ex.ToString());
ViewData["Message"] = ex.Message;
return View("Login");
}
}
else
{
logger.Info("" + returnUrl + "] LoginController : Authenticate method :when responce not null ");
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
logger.Info("" + response.Status + "] LoginController : Authenticate method : responce status ");
var fetchResponse = response.GetExtension<FetchResponse>();
string email = fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Email);
string userIPAddress = HttpContext.Request.UserHostAddress;
SecurityManager manager = new SecurityManager();
int userID = manager.IsValidUser(email);
if (userID != 0)
{
ViewBag.IsFailed = "False";
logger.Info("" + userID + "] LoginController : Authenticate method : user id id not null ");
Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay;
Session["UserEmail"] = email;
FormsAuthentication.SetAuthCookie(email, false);
WebSession.UserEmail = email;
WebSession.UserID = userID;
UserManager userManager = new UserManager();
WebSession.AssignedSites = userManager.GetAssignedSites(userID);
if (!string.IsNullOrEmpty(returnUrl))
{
logger.Info("" + returnUrl + "] LoginController : Authenticate method : retutn url not null then return Redirect ");
return Redirect(returnUrl);
}
else
{
logger.Info("" + returnUrl + "] LoginController : Authenticate method : retutn url null then return RedirectToAction ");
//
return Redirect("/Home");
}
}
else
{
ViewBag.IsFailed = "True";
logger.Info("" + returnUrl + "] LoginController : Authenticate method :user id null ");
if (!string.IsNullOrEmpty(returnUrl))
{
logger.Info("" + returnUrl + "] LoginController : Authenticate method :and return Redirect ");
return Redirect(returnUrl);
}
else
{
logger.Info("" + returnUrl + "] LoginController : Authenticate method :and return RedirectToAction ");
return View("Index");
}
}
case AuthenticationStatus.Canceled:
logger.Info("" + response.Status + "] LoginController : Authenticate method : AuthenticationStatus.Canceled and return view ");
ViewData["Message"] = "Canceled at provider";
return View("Login");
case AuthenticationStatus.Failed:
logger.Info("" + response.Status + "] LoginController : Authenticate method : AuthenticationStatus.Failed and return view ");
logger.Error(response.Exception.Message);
ViewData["Message"] = response.Exception.Message;
return View("Login");
}
}
logger.Info("" + returnUrl + "] LoginController : Authenticate method end and return EmptyResult");
return new EmptyResult();
}
catch (Exception ex)
{
logger.Error(" LoginController : Authenticate method ", ex);
throw;
}
}
Related
The problem i'm encountering is the moment i try switching from http to https, my unit tests fail and i can't push my code to production.
I'm trying to push some data from an apex class to another framework. Since this data might be a bit sensitive i'd like to encrypt it with the client certificate options offered by salesforce.
public class someclaass {
#future(callout=true)
public static void SendData(String id, String name, String token) {
HttpRequest req = new HttpRequest();
req.setEndpoint('https://someurl.com/');
req.setMethod('POST');
req.setHeader('content-type', 'application/json');
req.setClientCertificateName('certificatename');
req.setBody('{"id" : "' + id + '", "name" : "' + name + '", "token" : "' + token + '"}');
Http http = new Http();
HttpResponse res = http.send(req);
}
}
#istest
global class Some_mock implements HttpCalloutMock {
/* This method fakes a reponse to our HTTP request to Blue10 */
global HTTPResponse respond(HTTPRequest req) {
String endpoint = req.getEndpoint();
system.debug(endpoint);
System.assert(endpoint.startsWith('https://someurl.com'));
String responseBody = '';
String destination = '';
// get the actual API function we're calling
String[] parts = endpoint.split('/');
destination = parts[parts.size()-1];
system.debug(destination);
if(destination == 'sendData') {
System.assertEquals('POST', req.getMethod());
responseBody = Some_mock.SomeMock();
} else {
System.debug(LoggingLevel.ERROR, 'We don\'t have a test case for this API function yet: '+destination);
//System.assert(true == false);
}
// Create a fake response
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody(responseBody);
res.setStatusCode(200);
return res;
}
public static String SomeMock() {
String body =
' {'+
' "status": "success",'+
' "message": null,'+
' "code": 200'+
' }';
return body;
}
}
#isTest
private class SomeTest {
static testMethod void validateSomeClass() {
Test.setMock(HttpCalloutMock.class, new Some_mock());
Test.startTest();
Some.Senddata('id', 'name', 'token');
List<SomeInvocable.SomeVariable> SomeList = new List<SomeInvocable.SomeVariable>();
SomeInvocable.SomeVariable orobj = new SomeInvocable.SomeVariable();
orobj.id = 'id';
orobj.name = 'name';
orobj.token = 'token';
SomeList.add(orobj);
SomeInvocable.sendMessage(SomeList);
Test.stopTest();
}
}
The above works the moment i set http:// in both urls instead of https://, but i have no clue what i'm doing wrong here.
In my project I have implemented Spring Security. It's checking whether username and password is correct or not. I want to authenticate only username but not password. How can I achieve this?
public UserDetails loadUserByUsername(String username) {
if (lan == null) {
// loadPasswordRules();
}
List<UserDetails> users = loadUsersByUsername(username);
if (users.size() == 0) {
throw new AuthenticationServiceException("Username " + username + " is invalid ");
}
UserDetails user = users.get(0); // contains no IRole[]
/** Raising exception since start and expiry of user is not valid. */
/** Raising exception since start and expiry of user is not valid. */
Date todayDate = new Date();
if ( !((todayDate).after(((User) user).getStartDate()) && (todayDate).before(((User) user).getExpiryDate())) ) {
throw new AuthenticationServiceException("User " + username + " account is expired.");
/* throw new LockedException("User " + username + " account is expired.");
throw new UsernameNotFoundException("User {" + username + "} account is expired."); SPRING_SECURITY_LAST_EXCEPTION.message */
}
/*if ( ((User) user).getLastSuccessLogin() != null) {
Calendar newDate = Calendar.getInstance();
newDate.setTime( todayDate );
newDate.add(Calendar.DAY_OF_YEAR, - lan.intValue());
Calendar oldDate = Calendar.getInstance();
oldDate.setTime( ((User) user).getLastSuccessLogin() );
if (newDate.after(oldDate)) {
lockUserAccount(username);
throw new AuthenticationServiceException("User " + username + " account is expired.");
}
}*/
Set<IRole> dbAuthsSet = new HashSet<IRole>();
if (enableAuthorities) {
dbAuthsSet.addAll(loadUserAuthorities(user.getUsername()));
}
List<IRole> dbAuths = new ArrayList<IRole>(dbAuthsSet);
if (dbAuths.size() == 0) {
throw new AuthenticationServiceException("Username " + username + " has no assigned roles.");
}
((User) user).setRoles(dbAuths);
return user;
}
You should be able to accomplish this creating a custom AuthenticationProvider implementation and configure your AuthenticationManager to use that.
You should create a Custom Filter to due with this. The Filter should extends class AbstractAuthenticationProcessingFilter and return a Custom Authentication object. Then the Authentication Provider will see it and do check only username which is return by the Filter. After completing everything, you must do configure the Filter to Spring Security context to make it works.
You also can see my complete example here : http://phuonghuynh.github.io/java/spring/security/2015/09/06/spring-security-multiple-authentication-providers.html
I'm working on an application that uses Spring Security's searchForSingleEntryInternal method. Is there a way to do the same thing without throwing an exception if a record is not found? I want to be able to create a condition that handles missing records.
What I want to change
if (results.size() == 0) {
throw new IncorrectResultSizeDataAccessException(1, 0);
}
From this method
/**
* Internal method extracted to avoid code duplication in AD search.
*/
public static DirContextOperations searchForSingleEntryInternal(DirContext ctx, SearchControls searchControls,
String base, String filter, Object[] params) throws NamingException {
final DistinguishedName ctxBaseDn = new DistinguishedName(ctx.getNameInNamespace());
final DistinguishedName searchBaseDn = new DistinguishedName(base);
final NamingEnumeration<SearchResult> resultsEnum = ctx.search(searchBaseDn, filter, params, searchControls);
if (logger.isDebugEnabled()) {
logger.debug("Searching for entry under DN '" + ctxBaseDn + "', base = '" + searchBaseDn + "', filter = '" + filter + "'");
}
Set<DirContextOperations> results = new HashSet<DirContextOperations>();
try {
while (resultsEnum.hasMore()) {
SearchResult searchResult = resultsEnum.next();
// Work out the DN of the matched entry
DistinguishedName dn = new DistinguishedName(new CompositeName(searchResult.getName()));
if (base.length() > 0) {
dn.prepend(searchBaseDn);
}
if (logger.isDebugEnabled()) {
logger.debug("Found DN: " + dn);
}
results.add(new DirContextAdapter(searchResult.getAttributes(), dn, ctxBaseDn));
}
} catch (PartialResultException e) {
LdapUtils.closeEnumeration(resultsEnum);
logger.info("Ignoring PartialResultException");
}
if (results.size() == 0) {
throw new IncorrectResultSizeDataAccessException(1, 0);
}
if (results.size() > 1) {
throw new IncorrectResultSizeDataAccessException(1, results.size());
}
return results.iterator().next();
}
}
I'm somewhat new to spring and maybe I'm missing something obvious. Any advice would be much appreciated
easy fix, just had to copy over the searchForSingleEntryInternal method from Spring Security and place it in my own project. From there I was able to tweak the exception handling so the application didn't come to a grinding halt if a record wasn't found.
I am trying to add Google login in my universal app,For Windows 8.1 app,it's easy to do but in case of Windows Phone 8.1 WinRT app,
Here is the code I did:
private String simpleKey = "YOUR_SIMPLE_API_KEY"; // Should keep this secret
private String clientID = "ffffff- n12s9sab94p3j3vp95sdl7hrm2lbfk3e.apps.googleusercontent.com";
private string CALLBACKuri = "writeprovidedcallbackuri";
private String clientSecret = "LYffff2Q6MbgH623i"; // Keep it secret!
private String callbackUrl = "urn:ietf:wg:oauth:2.0:oob";
private String scope = "https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.email";
public GooglePlusLoginPage()
{
this.InitializeComponent();
refreshToken = null;
code = null;
access_token = null;
renderArea = this;
Auth();
}
public void Auth()
{
Windows.Storage.ApplicationData.Current.LocalSettings.Values["code"] = "";
if (access_token == null)
{
if (refreshToken == null && code == null)
{
try
{
String GoogleURL = "https://accounts.google.com/o/oauth2/auth?client_id=" + Uri.EscapeDataString(clientID) + "&redirect_uri=" + Uri.EscapeDataString(callbackUrl) + "&response_type=code&scope=" + Uri.EscapeDataString(scope);
System.Uri StartUri = new Uri(GoogleURL);
// When using the desktop flow, the success code is displayed in the html title of this end uri
System.Uri EndUri = new Uri("https://accounts.google.com/o/oauth2/approval?");
WebAuthenticationBroker.AuthenticateAndContinue(StartUri, EndUri, null, WebAuthenticationOptions.None);
// await Task.Delay(2);
}
catch (Exception Error)
{
((GooglePlusLoginPage)renderArea).SendToLangingPage();
}
}
}
//codeToAcccesTok();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
string name = e.Parameter as string;
IsGplusLogin = true;
// When the navigation stack isn't restored navigate to the ScenarioList
}
private void OutputToken(String TokenUri)
{
string access_token = TokenUri;
}
public void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args)
{
WebAuthenticationResult result = args.WebAuthenticationResult;
if (result.ResponseStatus == WebAuthenticationStatus.Success)
{
string response = result.ResponseData.ToString();
code = response.Substring(response.IndexOf("=") + 1);
Windows.Storage.ApplicationData.Current.LocalSettings.Values["code"] = code;
// TODO: switch off button, enable writes, etc.
}
else if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
{
//TODO: handle WebAuthenticationResult.ResponseErrorDetail.ToString()
}
else
{
((GooglePlusLoginPage)renderArea).SendToLangingPage();
// This could be a response status of 400 / 401
// Could be really useful to print debugging information such as "Your applicationID is probably wrong"
//TODO: handle WebAuthenticationResult.ResponseStatus.ToString()
}
codeToAcccesTok();
}
interface IWebAuthenticationContinuable
{
/// <summary>
/// This method is invoked when the web authentication broker returns
/// with the authentication result
/// </summary>
/// <param name="args">Activated event args object that contains returned authentication token</param>
void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args);
}
private async void codeToAcccesTok()
{
string oauthUrl = "https://accounts.google.com/o/oauth2/token";
HttpClient theAuthClient = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, oauthUrl);
// default case, we have an authentication code, want a refresh/access token
string content = "code=" + code + "&" +
"client_id=" + clientID + "&" +
"client_secret=" + clientSecret + "&" +
"redirect_uri=" + callbackUrl + "&" +
"grant_type=authorization_code";
if (refreshToken != null)
{
content = "refresh_token=" + refreshToken + "&" +
"client_id=" + clientID + "&" +
"client_secret=" + clientSecret + "&" +
"grant_type=refresh_token";
}
request.Method = HttpMethod.Post;
request.Content = new StreamContent(new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(content)));
request.Content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
try
{
HttpResponseMessage response = await theAuthClient.SendAsync(request);
parseAccessToken(response);
}
catch (HttpRequestException)
{
}
}
public async void parseAccessToken(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
//content="{\n \"error\" : \"invalid_request\",\n \"error_description\" : \"Missing required parameter: code\"\n}";
if (content != null)
{
string[] lines = content.Replace("\"", "").Replace(" ", "").Replace(",", "").Split('\n');
for (int i = 0; i < lines.Length; i++)
{
string[] paramSplit = lines[i].Split(':');
if (paramSplit[0].Equals("access_token"))
{
access_token = paramSplit[1];
}
if (paramSplit[0].Equals("refresh_token"))
{
refreshToken = paramSplit[1];
Windows.Storage.ApplicationData.Current.LocalSettings.Values["refreshToken"] = refreshToken;
}
}
//access_token="ya29.aAAvUHg-CW7c1RwAAACtigeHQm2CPFbwTG2zcJK-frpMUNqZkVRQL5q90mF_bA";
if (access_token != null)
{
getProfile();
}
else
{
((GooglePlusLoginPage)renderArea).SendToLangingPage();
// something is wrong, fix this
}
}
}
private async void ParseProfile(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
if (content != null)
{
var serializer = new DataContractJsonSerializer(typeof(UserEmail));
UserInfo = serializer.ReadObject(new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(content))) as UserEmail;
((GooglePlusLoginPage)renderArea).RenderUser();
WebView wb = new WebView();
var url = "http://accounts.google.com/Logout";
wb.Navigate(new Uri(url, UriKind.RelativeOrAbsolute));
}
}
public async void getProfile()
{
httpClient = new HttpClient();
var searchUrl = "https://www.googleapis.com/oauth2/v2/userinfo";
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + access_token);
try
{
HttpResponseMessage response = await httpClient.GetAsync(searchUrl);
ParseProfile(response);
}
catch (HttpRequestException hre)
{
// DebugPrint(hre.Message);
}
}
public async void RenderUser()
{
GridProgressRing.Visibility = Visibility.Visible;
Imageuri = UserInfo.picture.ToString().Replace("sz=50", "sz=150");
displayname = UserInfo.name;
Google_Id = UserInfo.id;
emailid = UserInfo.Email;
first_name = displayname;
uniqueName = Imageuri.ToString();
string Imagefile = "";
if (ShareMenuClass.CheckInternetConnection())
{
Imagefile = await ShareMenuClass.ToBase64String(Imageuri);
}
if (first_name.Contains(' '))
{
string[] dfdf = new string[2];
dfdf = first_name.Split(' ');
first_name = dfdf[0];
last_name = dfdf[1];
}
password = "google user";
string DataString = "<UserRegistration>" + "<FirstName>" + first_name + "</FirstName><LastName>" + last_name + "</LastName><Platform>Windows 8</Platform>" +
"<UUID>" + getDeviceId() + "</UUID><EmailId>" + emailid + "</EmailId><Password>" + password + "</Password><Photo>" + Imagefile +
"</Photo><OrganiztionName>" + organization_name + "</OrganiztionName><Location>indore</Location><AppId>2</AppId><querytype>register</querytype></UserRegistration>";
if (ShareMenuClass.CheckInternetConnection())
{
string Front = "<UserRegistration xmlns=\"www.XMLWebServiceSoapHeaderAuth.net\"> <UserRegistrationXml>";
string Back = "</UserRegistrationXml></UserRegistration>";
DataString = DataString.Replace("<", "<");
DataString = DataString.Replace(">", ">");
DataString = Front + DataString + Back;
string RecivedString = await ShareMenuClass.CallWebService("UserRegistration", DataString);
bool flagtoFillDefaultProgress = true;
if (RecivedString.Contains("Email Id is already registered"))
{
flagtoFillDefaultProgress = false;
string SoapXml = "<getuserProgressInfo><EmailId>" + emailid + "</EmailId><AppId>2</AppId></getuserProgressInfo>";
Front = "<getuserProgress xmlns=\"www.XMLWebServiceSoapHeaderAuth.net\"><getuserProgressInfoXml>";
Back = "</getuserProgressInfoXml></getuserProgress>";
SoapXml = SoapXml.Replace("<", "<");
SoapXml = SoapXml.Replace(">", ">");
SoapXml = Front + SoapXml + Back;
RecivedString = await ShareMenuClass.CallWebService("getuserProgress", SoapXml);
}
if (RecivedString.Contains("success"))
{
txtplswait.Text = "Configuring your account...";
RecivedXml.RecivedStringToObserCollection(RecivedString);
//if (flagtoFillDefaultProgress)
//{
await System.Threading.Tasks.Task.Delay(25);
await RecivedXml.FillMyHalfList();
//}
RecivedXml.SerializeRecivedRecivedollection();
ShareMenuClass.Google_Loging = true;
if (RecivedXml.WholeRecivedData[0].response == "success")
{
StorageFile storagefile = await ApplicationData.Current.LocalFolder.CreateFileAsync("IsGoogleUser.txt", CreationCollisionOption.ReplaceExisting);
RecivedXml.SerializeSignedUserInfo(RecivedXml.WholeRecivedData[0].Id);
Quizstatemodleobj.GetOverallQuizProgressForAllUserAndFillThisUserList(RecivedXml.WholeRecivedData[0].Id);
await System.Threading.Tasks.Task.Delay(25);
GridProgressRing.Visibility = Visibility.Collapsed;
Frame.Navigate(typeof(TrainingModulesPage));
}
}
else
{
MessageDialog msg1 = new MessageDialog("Somthing went wrong.Try again later!");
await msg1.ShowAsync();
Frame.Navigate(typeof(RegistrationPage));
}
}
else
{
MessageDialog msg1 = new MessageDialog("You are not connected to internet!");
await msg1.ShowAsync();
Frame.Navigate(typeof(RegistrationPage));
}
}
public Page renderArea { get; set; }
public string refreshToken { get; set; }
public string code { get; set; }
Here in ContinueWebAuthentication which is triggered after user accepts to let the app get the profile info the value of "code" is not the desired one,In W8.1 app the value of "code" is correct but here it is not.
Due to this I am unable to get the user profile info
I finally figured this out.
Change the "redirect_uri" query parameter in the "StartUri" parameter of the AuthenticateAndContinue method to http://localhost
Change the CallbackURL (or "EndUri") parameter of the "AuthenticateAndContinue" method to also equal http://localhost
After many hours this is what worked for me. I found the answer by browsing the code at: http://code.msdn.microsoft.com/windowsapps/Authentication-using-bb28840e and specifically looking at the class "GoogleService.cs" in the Authentication.Shared project of the solution.
Hope this helps.
I want to use HttpSession in Spring 3 MVC. I have searched all the web and got this solution at http://forum.springsource.org/showthread.php?98850-Adding-to-stuff-to-the-session-while-using-ResponseBody
Basically, my application auto authenticates user by getting winId and authorizes through LDAP (it's an intranet site).
Here is the flow of the application:
User enters Application URL (http://localhost:8082/eIA_Mock_5) it has a welcome page (index.jsp)
index.jsp gets winId through jQuery and hits login.html (through AJAX) and passes windowsId
login.html (Controller) authenticates through LDAP and gives back 'Valid' String as a response
JavaScript, upon getting the correct response, redirects/loads welcome page i.e. goes to localhost:8082/eIA_Mock_5/welcome.html
Now, I have filter associated with it, which checks if the session is valid for each incoming request. Now the problem is even though I set data on to HttpSession, yet the filter or any other controller fails to get the data through session as a result it doesn't proceeds further.
Here is the code. Could you suggest what is wrong actually?
Home_Controller.java:
#Controller
public class Home_Controller {
public static Log logger = LogFactory.getLog(Home_Controller.class);
#RequestMapping(value = {"/welcome"})
public ModelAndView loadWelcomePage(HttpServletRequest request, HttpServletResponse response)
{
ModelAndView mdv = new ModelAndView();
try {
/*HttpSession session = request.getSession();
UserMasterBean userBean = (UserMasterBean)session.getAttribute("userBean");
String userName = userBean.getWindowsId();
if(userName == null || userName.equalsIgnoreCase(""))
{
mdv.setViewName("homePage");
System.out.println("Unable to authenticate user ");
logger.debug("Unable to authenticate user ");
}
else
{
System.out.println("Welcome User "+userName);
logger.debug("Welcome User "+userName);
*/
mdv.setViewName("homePage");
/*}*/
}
catch (Exception e){
logger.debug("inside authenticateUser ",e);
e.printStackTrace();
}
return mdv;
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public #ResponseBody String authenticateUser(#RequestParam String userName, HttpSession session)
{
logger.debug("inside authenticateUser");
String returnResponse = new String();
try {
logger.debug("userName for Authentication " + userName);
System.out.println("userName for Authentication " + userName);
//HttpSession session = request.getSession();
if (userName == null || userName.trim().equalsIgnoreCase(""))
returnResponse = "Invalid";
else
{
System.out.println("uname " + userName);
String ldapResponse = LDAPConnectUtil.isValidActiveDirectoryUser(userName, "");
if (ldapResponse.equalsIgnoreCase("true"))
{
returnResponse="Valid";
System.out.println(userName + " Authenticated");
logger.debug(userName + " Authenticated");
UserMasterBean userBean = new UserMasterBean();
userBean.setWindowsId(userName);
//if(session.getAttribute("userBean")==null)
session.setAttribute("userBean", userBean);
}
else
{
returnResponse = "Invalid";
//session.setAttribute("userBean", null);
System.out.println("Unable to Authenticate the user through Ldap");
logger.debug("Unable to Authenticate the user through Ldap");
}
System.out.println("ldapResponse " + ldapResponse);
logger.debug("ldapResponse " + ldapResponse);
System.out.println("returnResponse " + returnResponse);
}
UserMasterBean u = (UserMasterBean)session.getAttribute("userBean");
System.out.println("winId " + u.getWindowsId());
}
catch(Exception e){
e.printStackTrace();
logger.debug("Exception in authenticateUser ", e);
}
return returnResponse;
}
}
Filter:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
{
System.out.println("in PageFilter");
boolean flag = false;
HttpServletRequest objHttpServletRequest = (HttpServletRequest)request;
HttpServletResponse objHttpServletResponse = (HttpServletResponse)response;
HttpSession session = objHttpServletRequest.getSession();
String contextPath = objHttpServletRequest.getContextPath();
String servletPath = objHttpServletRequest.getSession().getServletContext().getRealPath(objHttpServletRequest.getServletPath());
logger.debug("contextPath :" + contextPath);
logger.debug("servletPath :" + servletPath);
System.out.println("in PageFilter, contextPath :" + contextPath);
System.out.println("in PageFilter, servletPath :" + servletPath);
if (servletPath.endsWith("\\") || servletPath.endsWith("/") ||
servletPath.indexOf("css") > 0 || servletPath.indexOf("jsp") > 0 ||
servletPath.indexOf("images") > 0 || servletPath.indexOf("js") > 0 ||
servletPath.endsWith("index.jsp") || servletPath.indexOf("xls") > 0 ||
servletPath.indexOf("ini") > 0 || servletPath.indexOf("login.html") > 0 ||
/*servletPath.endsWith("welcome.html") ||*/ servletPath.endsWith("logout.do") )
{
System.out.println("User is trying to access allowed pages like Login.jsp, errorPage.jsp, js, images, css");
logger.debug("User is trying to access allowed pages like Login.jsp, errorPage.jsp, js, images, css");
flag = true;
}
if (flag == false)
{
System.out.println("flag = false");
if (session.getAttribute("userBean") == null)
System.out.println("yes session.userbean is null");
if ((session != null) && (session.getAttribute("userBean") != null))
{
System.out.println("session!=null && session.getAttribute(userId)!=null");
logger.debug("IF Part");
UserMasterBean userBean = (UserMasterBean)session.getAttribute("userBean");
String windowsId = userBean.getWindowsId();
logger.debug("User Id " + windowsId + " allowed access");
System.out.println("User Id " + windowsId + " allowed access");
flag = true;
}
else
{
System.out.println("else .....session!=null && session.getAttribute(userId)!=null");
logger.debug("Else Part");
flag = false;
}
}
if (flag == true) {
try {
System.out.println("before chain.doFilter(request, response)");
chain.doFilter(request, response);
} catch (Exception e) {
e.printStackTrace();
try {
objHttpServletResponse.sendRedirect(contextPath + "/logout.do");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
else
{
try {
System.out.println("before sendRedirect");
objHttpServletResponse.sendRedirect(contextPath + "/jsp/errorPage.jsp");
} catch (Exception ex) {
ex.printStackTrace();
}
}
System.out.println("end of PageFilter");
}
index.jsp:
<script type="text/javascript">
//alert("inside s13");
var WinNetwork = new ActiveXObject("WScript.Network");
var userName = WinNetwork.UserName;
alert(userName);
$.ajax({
url: "login.html",
data: "userName="+userName,
success: function(result) {
alert("result == " + result);
if (result == "Valid")
window.location = "http://10.160.118.200:8082/eIA_Mock_5/welcome.html";
}
});
</script>
web.xml has a filter entry with URL pattern as *
I am using Spring 3 MVC.
I think problem in ajax call and setting windows.location after that.
Make sure you set cookie enabled. If you don't do this, your ajax request will lead to new session every time.
When you do window.location = url and this url differ than your current url, it also lead to new session, because cookie is domain related, and you changed domain, for example from localhost to 10.160.118.200.
For each request output sessionid and compare it with previous request. It helps find when session was recreated.
Also this answer can help.