Selasa, 29 Juli 2014

Role based Access control using Spring Security and MVC, Mapping LDAP Groups to Authorities for Authorization



Authentication and Authorization is integral part of any Java enterprise
or web application. Since most of the company uses LDAP Active directory for authentication, authorization and Role based access control (RBAC), it's good
to know How to implement Role based
access control using Spring MVC and Spring Security
. This is the second
part of my articles on using Spring Security for authentication and
authorization in Spring MVC based Java application. In last part, we have
learned about doing LDAP authentication against Windows
active directory
, a
nd in this Spring
Security tutorial
, we will learn How to map LDAP groups to authorities for
implementing Role based access control or authorization. If you are developing
an application, whose access is controled by adding user to a particular LDAP
group, then you need a mechanism to load those LDAP group after successful
authentication. Spring Secuirty uses
GrantedAuthority class for
holding all roles for a particular user. Based upon these roles, a particular
user can perform certain functionality in your application. For example, a read
only user can only see data, but a user with ADMIN role, can add or remove data
from your application. After implementing Role based access control, you are free
of user management task, those will be taken care by respective team which
manages LDAP groups and access, usually Windows support teams. In this
article, we will all the steps required to map LDAP groups to granted authorities in Spring Security. If you love to read books, than you may want to
check Spring Security 3.1 By Robert Winch,Peter Mularien, a great book, which teaches all good features of
Spring security including LDAP authentication and authorization in great
details. If you are developing secure enterprise application in Java and
considering spring security, this is the one of the best and must read book on
Spring Security.





  


Steps to Map LDAP groups to Authorities for
Role based Access Control (RBAC)



Mapping LDAP authorities into role based access Java spring security example1) Create an Application specific Authority classes, usually an enum with
values like APP_USER, APP_ADMIN





2) Create Authority Mapper which will Map LDAP groups to application
specific authority for example if group in LDAP is "Application Access
(Gn)" than mapping that to APP_USER.





3) If you are authenticating against Active directory than provide your
custom Authority mapper to
ActiveDirectoryLdapAuthenticationProvider. After
successful authentication, it will load all the groups for which authenticated
user_id is member of, and map with application specific authority.





4) Use application specific authorities or roles as APP_USER or APP_ADMIN
to secure your URL's by using


<intercept-url pattern="/secure/admin/**" access="hasRole('APP_ADMIN')"/>

 

<intercept-url pattern="/secure/user/**" access="hasRole('APP_USER')"/>

<intercept-url pattern="/secure/**" access="isAuthenticated()" />









Java code for Mapping LDAP Groups to
Authorities using Spring Security



Here is the Java code, required to map LDAP groups into granted
authorities of Spring Security. We need one class, usually enum to create roles
supported by our application, this must implement
GrantedAuthority interface,
which is used to represent role in Spring Security. Now we need a Mapper class
to map LDAP groups into granted authorities, this class must implement
GrantedAuthoritiesMapper interface.
We create instance of this class using Spring and provide names of LDAP groups
for mapping with a particular role. For example, if application has two  roles USER and ADMIN and LDAP group
"Application
User Access (Gn)"
is for User and "Application Admin
Access (Gn)"
is for Admin, then this information is configured
in Spring configuration file and this authority mapper is provided to LDAP authentication provider. Keeping application role separate from LDAP groups
allows you to cope up with any change in LDAP group name, you just need to
change your spring configuration file.





LDAPGrantedAuthoritiesMapper.java


import java.util.Collection;

import java.util.EnumSet;

import java.util.Set;

import org.springframework.security.core.GrantedAuthority;

import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;

 

/**

 * LDAP Authorities mapper, Maps LDAP groups to APP_USER and APP_ADMIN

 */

public class LDAPGrantedAuthoritiesMapper implements GrantedAuthoritiesMapper {

    private final String APP_USER ="Ldap User Group";   //default user ldap group

    private final String APP_ADMIN ="Ldap Admin Group"; //default adming ldap group

 

    public ADGrantedAuthoritiesMapper(String userGroup, String adminGroup) {

        APP_USER = userGroup;

        APP_ADMIN = adminGroup;

 

    }

 

    public Collection  mapAuthorities(

            final Collection authorities) {

 

        Set roles = EnumSet.noneOf(LDAPAuthority.class); //empty EnumSet

 

        for (GrantedAuthority authority : authorities) {

            if (APP_USER.equals(authority.getAuthority())) {

                roles.add(LDAPAuthority.APP_USER);

            } else if (APP_ADMIN.equals(authority.getAuthority())) {

                roles.add(LDAPAuthority.APP_ADMIN);

            }

        }

        return roles;

    }

}






LDAPAuthority.java


import org.springframework.security.core.GrantedAuthority;

 

/**

 * Maps LDAP Group application roles

 */

public enum LDAPAuthority implements GrantedAuthority{

    APP_USER, APP_ADMIN; //roles used in application

   

    public String getAuthority() {

        return name();

    }

   

}






Spring Security Configuration for Role based
Access and Mapping LDAP groups



As stated above, first configuration is creating an instance of LDAPGrantedAuthoritiesMapper and
mapping LDAP groups to application roles, so that when a user is successfully
authenticated and comes with all LDAP groups, he is member of, those groups
are read and converted into corresponding roles. Second configuration is to
provide this mapper to
ActiveDirectoryLdapAuthenticationProvider, this is
similar to our last example of LDAP authentication, except <
beans:property
name="authoritiesMapper" ref="ldapAuthoritiesMapper"/>
, which is
requite to map LDAP groups to granted authorities for role based access
control.






<beans:bean id="ldapAuthoritiesMapper" class="com.abc.web.security.LDAPGrantedAuthoritiesMapper">

        <beans:constructor-arg value="Ldap User Group" />

        <beans:constructor-arg value="Ldap Admin Group" />

beans:bean>   

 

<beans:bean id="LdapAuthProvider"  class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">

        <beans:constructor-arg ref="domain" />

        <beans:constructor-arg ref="url" />

        <beans:property name="convertSubErrorCodesToExceptions" value="true"/>

        <beans:property name="authoritiesMapper" ref="ldapAuthoritiesMapper"/>   //LDAP authority mapper

        <beans:property name="useAuthenticationRequestCredentials" value="true"/>

beans:bean


 




That's all you need to implement Role based access control on your Spring
MVC, Spring Security based Java web application. Like other features, LDAP
authorization doesn't come out of box from Spring Security and you need to
follow above steps to map LDAP groups to granted authorities.





Recommended
Book:


Spring Security 3.1 By Robert Winch,Peter Mularien is one of the best and must read book on Spring
security. It takes application development approach to teach basics of
enterprise security, LDAP concepts, authentication, authorization and several
other spring security features with non trivial examples.



























Source:http://javarevisited.blogspot.com/2013/07/role-based-access-control-using-spring-security-ldap-authorities-mapping-mvc.html

Anti-Tech Security Hysteria

When the security hysterics among us get their feathers in a bunch, the first thing they seek to do to assuage their irrational fears is to demands that the rest of us comply with their insane proposals, no matter how inimical they are to liberty, rights or even security itself.  Tech Dirt takes down a prime example of anti-tech hysteria at the Washington Post:
Every time I think I've read the least well-thought out luddite argument, someone comes along to top it, and today we have columnist Robert Samuelson in the Washington post with what might be the silliest, most lacking-in-thought argument for why we should get rid of the internet. The short version: yes, the internet has provided us with some good stuff, but because there's a yet unproven risk that it might also lead to some cyberattacks that might lead to as yet undetermined problems, we should scrap the whole thing. Oddly, the WaPo had put different titles on the piece online and in the print newspaper. Online, it's entitled: "Beware the Internet and the danger of cyberattacks." In the physical paper, they apparently went with the much more ridiculous: "Is the Internet Worth It?" with the clear implication being a fulfillment of Betteride's Law that the answer is "no, the internet is not worth it."

Source:http://blog.agupieware.com/2013/07/anti-tech-security-hysteria.html

The NSA&#39;s Vast Spying Regime Does Not Pass Constitutional Muster

It often appears that the only time Democrats and Republicans can agree on anything, it tends to result in the launching of new wars, or building more prisons, or further eroding constitutional rights and civil liberties.  This could not be more clear in the bipartisan defense of the unconstitutional surveillance and spying regime that has been constructed in the United States over the last decade(s).  An op-ed in the New York Times calls it what it is: criminal.  Excerpt:
The Fourth Amendment obliges the government to demonstrate probable cause before conducting invasive surveillance. There is simply no precedent under the Constitution for the government’s seizing such vast amounts of revealing data on innocent Americans’ communications. 

The government has made a mockery of that protection by relying on select Supreme Court cases, decided before the era of the public Internet and cellphones, to argue that citizens have no expectation of privacy in either phone metadata or in e-mails or other private electronic messages that it stores with third parties . . . 

We may never know all the details of the mass surveillance programs, but we know this: The administration has justified them through abuse of language, intentional evasion of statutory protections, secret, unreviewable investigative procedures and constitutional arguments that make a mockery of the government’s professed concern with protecting Americans’ privacy. It’s time to call the N.S.A.’s mass surveillance programs what they are: criminal.

Source:http://blog.agupieware.com/2013/06/the-nsas-vast-spying-regime-does-not.html

Senin, 28 Juli 2014

10 Java Exception and Error Interview Questions Answers




You will always see some interview questions from Exception and Error
handling in core Java Interviews. Exception handling is an important aspect of
Java application development and its key to writing robust, stable Java programs,
which makes it natural favorites on interviews. Questions from Error and
Exception in Java mostly based on concept of Exception and Error in Java, How
to handle Exception , best
practices to follow during Exception handling
etc. Though multithreading,
garbage collection, JVM concepts and questions from object oriented design
rules these interviews, you should always expect and prepare some questions on
effective error handling. Some Interviewer also  test debugging skill of programmers, as
resolving Exceptions quickly is another trait of solid Java programming
knowledge. If programmer is familiar with infamous and dodgy ClassNotFoundException
or OutOfMemoryError,
there is a good chance that he has some good practical experience under his
belt. In this article we will see some Java Error and Exception interview
questions asked to fresher, experienced and senior Java developers in Java J2EE
interviews.







Java Exception and Error Interview Questions



Java Exception and Error Interview Question AnswersHere is my list of frequently asked questions from Java Error and
Exception topics in various programming interviews to Java and J2EE
developers.  I have also shared my
answers for these questions for quick revision, and provided source for more in depth understanding. I have tried to include questions of various difficulty
level, including simplest of simple for freshers and some tricky questions for
senior Java developers. If you think, there is a good question, which is not
included in this list, please feel free to share it via comment. You can also
share error handling questions asked to you on interviews or any question, for
which you don’t know the answer.








1) What
is Exception in Java?


This is always been first interview question on Exception and mostly
asked on fresher level interviews. I haven't seen anybody asking about what is
Exception in senior and experienced level interviews, but this is quite popular
at entry level. In simple word Exception is Java’s way to convey both system
and programming errors. In Java Exception feature is implemented by using class
like
Throwable, Exception, RuntimeException and
keywords like
throw, throws, try, catch and finally. All
Exception are derived form
Throwable class.
Throwable further divides errors in too category one is
java.lang.Exception and other
is
java.lang.Error.  java.lang.Error deals with
system errors like
java.lang.StackOverFlowError or Java.lang.OutOfMemoryError
while Exception is mostly used to deal with programming mistakes, non
availability of requested resource etc.





2) What
is difference between Checked and Unchecked Exception in Java ?


This is another popular Java Exception interview question appears in
almost all level of Java interviews. Main difference between Checked and
Unchecked Exception lies in there handling. Checked Exception requires to be
handled at compile time using
try, catch and finally keywords
or else compiler will flag error. This is not a requirement for Unchecked
Exceptions. Also all exceptions derived from
java.lang.Exception classes
are checked exception, exception those which extends
RuntimeException,
these are known as unchecked exception in Java. You can also check next
article for more
differences between Checked and Unchecked Exception
.





3) What
is similarity between NullPointerException and ArrayIndexOutOfBoundException in
Java?


This is Java Exception interview question was not very popular, but
appears in various fresher level interviews, to see whether candidate is
familiar with concept of checked and unchecked exception or not. By the way
answer of this interview question is both of them are example of unchecked
exception and derived form
RuntimeException. This
question also opens door for difference of array in Java and C programming
language, as arrays in C are unbounded and never throw
ArrayIndexOutOfBoundException.





4) What
best practices you follow while doing Exception handling in Java ?


This Exception interview question in Java is very popular while hiring
senior java developer of Technical Lead. Since exception handling is crucial
part of project design and good knowledge of this is desirable. There are lot
of best practices, which can help to make your code robust and flexible at same
time, here are few of them:





1) Returning boolean instead of returning null to avoid
NullPointerException at callers end. Since NPE is most infamous of all Java exceptions,
there are lot of techniques and coding
best practices to minimize NullPointerException
. You can check that link
for some specific examples.





2) Non empty catch blocks. Empty catch blocks  are considered as one of the bad practices in
Exception handling because they just ate Exception without any clue, at bare
minimum print stack trace but you should do alternative operation which make
sense or defined by requirements.





3) Prefer Unchecked exception over checked until you have a very good
reason of not to do so. it improves readability of


code by removing boiler plate exception handling code


.


4) Never let your database Exception flowing till client error. since
most of application deal with database and SQLException
is a checked Exception in Java you should consider handling any database
related errors in DAO layer of your application and only returning alternative
value or something meaningful
RuntimeException which
client can understand and take action.





5) calling close() methods for connections,
statements, and streams on finally block in Java.





I have already shared lot of these in my post Top
10 Java exception handling best practices
, you can also refer that for more
knowledge on this topic.





5) Why do
you think Checked Exception exists in Java, since we can also convey error
using RuntimeException ?


This is a controversial question and you need to be careful while
answering this interview question. Though they will definitely like to hear
your opinion, what they are mostly interested in convincing reason. One of the
reason I see is that its a design decision, which is influenced by experience
in programming language prior to Java e.g. C++. Most of checked exceptions are
in
java.io package, which make sense because if you request any system resource and
its not available, than a robust program must be able to handle that situation
gracefully. By declaring
IOException as checked Exception, Java ensures
that your provide that gracefully exception handling. Another possible reason
could be to ensuring that system resources like file descriptors, which are
limited in numbers, should be released as soon as you are done with that using
catch or finally block. Effective Java book from Joshua Bloch has couple of items in this topic, which is again
worth reading.





6) What
is difference between throw and throws keyword in Java?


One more Java Exception interview questions from beginners kitty. throw and throws keyword
may look quite similar, especially if you are new to Java programming and
haven't seen much of it. Though they are similar in terms that both are used in
Exception handling, they are different on how and where they are used in code.
throws keyword is
used in method signature to declare which checked exception method can throw,
you can also declare unchecked exception, but that is not mandatory by compiler.
This signifies lot of things like method is not going to handle Exception
instead its throwing it, if method throws checked Exception then caller should
provide compile time exception handling etc. On the other hand
throw keyword is
actually used to throw any Exception. Syntactically you can throw any
Throwable (i.e. Throwable or any
class derived from
Throwable) , throw  keyword transfers control of execution to
caller so it can be used in place of return keyword. Most common example of
using throw in place of return is throwing
UnSupportedOperationException from an
empty method as shown below :





private static void show() {


    throw new
UnsupportedOperationException("Not yet implemented");


}





See this
article
for more differences between these two keywords in Java.





7) What
is Exception chaining in Java?


Exception chaining is a popular exception handling concept in Java, where
another exception is thrown in response of an exception and creating a chain of
Exceptions. This technique mostly used to wrap a checked exception into an
unchecked or
RuntimeException. By the way if you are
throwing new exception due to another exception then always include original
exception so that handler code can access root cause by using methods like
getCause() and initCause().





8) Have
you written your own custom Exception in Java? How do you do that?


Ofcourse most of us has written custom or business Exceptions like AccountNotFoundExcepiton. Main
purpose of asking this Java Exception interview question is to find out how you
use this feature. This can be used for sophisticated and precise exception
handling with tweak involved in whether you would choose a checked or unchecked
exception. By creating a specific exception for specific case, you also gives
lot of options to caller to deal with them elegantly. I always prefer to have a
precise exception than a general exception. Though creating lots of specific
exceptions quickly increase number of classes in your project, maintaining a
practical balance between specific and general exceptions are key to success.








9) What
changes has been introduced in JDK7 related to Exception handling in Java ?


A relatively new and recent Exception interview question in Java. JDK7
has introduced two major feature which is related to Error and Exception
handling,  one is ability to handle multiple
exception in one catch block
, popularly known as multi cache block and
other is ARM
blocks in Java 7
for automatic resource management, also known as try with
resource. Both of these feature can certainly help to reduce boiler plate code
required for handling checked exceptions in Java and significantly improves
readability of code. Knowledge of this feature, not only helps to write better error and exception code in Java, but also helps to do well during interviews. I
also recommend reading Java 7 Recipes
book to get more insight on useful features introduced in Java 7, including
these two.





10) Have
you faced OutOfMemoryError in Java? How did you solved that?


This Java Error interview questions is mostly asked on senior level Java
interviews and here interviewer is interested on your approach to tackle
dangerous
OutOfMemoryError. Admit it we always face this
error no matter which kind of project you are working so if you say no it
doesn't go very well with interviewer. I suggest even if you are not familiar
or not faced it in reality but have 3 to 4 years of experience in Java, be
prepare for it. At the same time, this is also a chance to impress interviewer
by showing your advanced technical knowledge related to finding memory leaks,
profiling and debugging. I have noticed that these skills almost always creates
a positive impression. You can also see my post on how
to fix java.lang.OutOfMemoryError
for more detail on this topic.





11) Does
code form finally executes if method returns before finally block or JVM exits
?


This Java exception interview question can also be asked in code format,
where given a code with
System.exit() in try block and something in
finally block. It’s worth knowing that, finally block in Java executes even
when return keyword is used in try block. Only time they don’t execute is when you
call JVM to exit by executing
System.exit(0)from try
block in Java.








12) What
is difference in final, finalize and finally keyword in Java?


Another classic interview question in core Java, this was asked to one of
my friend on his telephonic interview for core Java developer with Morgan
Stanley.
final and finally are
keyword, while
finalize is method. final keyword is very
useful for creating ad Immutable
class in Java
By making a class final, we prevent it from being extended,
similarly by making a method final, we prevent it from being overridden,. On
the other hand,
finalize() method is called  by garbage collector, before that object is
collected, but this is not guaranteed by Java specification.
finally keyword is
the only one which is related to error and exception handling and you should
always have finally block in production code for closing connection and
resources. See here
for more detailed answer of this question.











13) What
is wrong with following code :





 public static void start() throws IOException, RuntimeException{


   
throw new RuntimeException("Not able to Start");


 }





 public static void main(String args[]) {


   
try {


          start();


   
}
catch (Exception ex) {


            ex.printStackTrace();


   
}
catch (RuntimeException re) {


            re.printStackTrace();


   
}


 }









This code will throw compiler error on line where RuntimeException  variable “re” is written
on catch block. since Exception is super class of
RuntimeException, all RuntimeException thrown by start() method
will be captured by first catch block and code will never reach second catch
block and that's the reason compiler will flag error as  “exception
java.lang.RuntimeException has already been caught".








14) What
is wrong with following code in Java:






public class SuperClass
{  


   
public void
start() throws IOException{


        throw new IOException("Not able
to open file"
);


   
}


}





public class SubClass
extends SuperClass{  


   
public void
start() throws Exception{


        throw new Exception("Not able
to start"
);


   
}


}






In this code compiler will complain on sub class where start() method
gets overridden. As per rules
of method overriding in Java
, an overridden method can not throw Checked
Exception which is higher in hierarchy than original method. Since here
start() is
throwing
IOException in super class, start() in sub
class can only throw either
IOException or any sub
class of IOException but not super class of
IOException e.g.
Exception.





15) What
is wrong with following Java Exception code:






public static void start(){


  
System.
out.println("Java Exception interivew question Answers for
Programmers"
);


}





public static void main(String args[]) {


  
try{


      start();


  
}
catch(IOException ioe){


      ioe.printStackTrace();


  
}


}



  


In this Java Exception example code, compiler will complain on line where
we are handling
IOException, since IOException is a
checked Exception and
start() method doesn't throw IOException, so
compiler will flag error as "
exception
java.io.IOException is never thrown in body of corresponding try statement
", but
if you change
IOException to Exception compiler error will
disappear because Exception can be used to catch all
RuntimeException which
doesn't require declaration in throws clause. I like this little tricky Java
Exception interview question because its not easy to figure out result by chaining
IOException to Exception. You can
also check Java Puzzlers by Joshua Bloch and Neil Gafter for some tricky questions based
on Java Errors and Exceptions.





These are some of Java Error and Exception interview questions, I have
mostly seen in both fresher and experienced level of Java interviews. There are
a lot more questions on Exception which I haven't included and if you think you
have a good question missed out than let me know and I will make effort to
include it on this list of java exceptions question and answers. One last
question of Java Exception I am leaving for you guys is
"Why
Java Exception considered to be better alternative of returning error codes
" ,
let me know what is your thought on this list of Java Exception interview
questions and answers.









Recommended Books in this article





Effective Java
By Joshua Bloch


Java 7Recipes: A Problem-Solution Approach By Josh Juneau, Carl Dea, Freddy Guime
and John O'Conner


Java Puzzlers
by Joshua a Bloch and Neil Gafter































Source:http://javarevisited.blogspot.com/2013/06/10-java-exception-and-error-interview-questions-answers-programming.html

Documents Reveal Widespread Email Surveillance by US Government for Past Decade

A few years ago, actually, even just a few weeks ago, anyone who suggested that email correspondence and internet traffic were being monitored by the government would have been labeled a nut or conspiracy theorist.  But they would have been right.  From The Guardian:
The Obama administration for more than two years permitted the National Security Agency to continue collecting vast amounts of records detailing the email and internet usage of Americans, according to secret documents obtained by the Guardian.

The documents indicate that under the program, launched in 2001, a federal judge sitting on the secret surveillance panel called the Fisa court would approve a bulk collection order for internet metadata "every 90 days". A senior administration official confirmed the program, stating that it ended in 2011.

The collection of these records began under the Bush administration's wide-ranging warrantless surveillance program, collectively known by the NSA codename Stellar Wind.

Source:http://blog.agupieware.com/2013/06/documents-reveal-widespread-email.html

Automatically set Everyplace start center for mobile users

Maximo Everyplace is the easiest solution to go mobile with Maximo however there is one little thing that always annoys me (and mobile users).

After having created mobile versions of the Maximo apps, the administrator has to define a mobile start center with a Favorite Applications portlet to access them. Unfortunately, there is no way to set this as a 'mobile' Start Center so each user have to click on the Display Settings link and select the Is Mobile check box for the specific start center.

In the real world this means that after having set up Maximo Everyplace I have to send an email to all the mobile users with the instructions about how to setup their mobile start center.

Here is a simple escalation to automatically set the Is Mobile checkbox for the designated start center for all the users.

First of all we need an Action to set the flag:
  • Action: SETMSC
  • Description: Set Mobile Start Center
  • Object: SCCONFIG
  • Type: Set Value
  • Attribute: ISMOBILE
  • Value: 1
  • Accessible From: ESCALATION

Then we can define the Escalation to run the action:
  • Name: SETMSC
  • Description: Set Mobile Start Cente
  • Condition: groupname in ('[EVGROUP]') and ismobile=0
  • Schedule: hourly
  • Create Successful Execution Entry?: No
  • Escalation point: Empty
  • Action: SETMSC

The [EVGROUP] should match the name of your Security Group(s) with the mobile start center assigned.


Source:http://maximodev.blogspot.com/2013/06/set-maximo-everyplace-start-center-mobile.html