Vaadin & Shiro navigation - vaadin

I use shiro-vaadin-integration plugin
#WebServlet(urlPatterns = "/*", name = "Test", asyncSupported = true,
initParams = #WebInitParam(name = Constants.I18N_PROVIDER,
value = "com.test.TranslationProvider"))
#VaadinServletConfiguration(productionMode = false)
#Slf4j
public class AppServlet extends VaadinServlet {
#Override
protected void servletInitialized() throws ServletException {
log.info("Init Shiro");
IniRealm iniRealm = new IniRealm("classpath:shiro.ini");
DefaultSecurityManager securityManager = new DefaultSecurityManager(iniRealm);
// SessionDAO sessionDAO = new MemorySessionDAO();
// ((DefaultSessionManager) securityManager.getSessionManager()).setSessionDAO(sessionDAO);
// securityManager.setCacheManager(new MemoryConstrainedCacheManager());
SecurityUtils.setSecurityManager(securityManager);
log.info("Finish Init Shiro");
super.servletInitialized();
}
The crux of the problem is that after logging in. I throws on the main page.
SecurityUtils.getSubject().isAuthenticated()
Return true.
Further, when trying to navigate in the application.
SecurityUtils.getSubject().isAuthenticated()
Return false.
It feels like a session lasts a couple of seconds
shiro.ini
[main]
authc.loginUrl = /signin
vaadin = org.vaadin.shiro.VaadinNavigationRolesAuthorizationFilter
vaadin.loginUrl = /signin
[users]
admin#admin.com = 1#QWaszx, admin
user = user, user
[roles]
admin = *
user = action1:*
[urls]
/ = anon, vaadin
/signin = anon, vaadin
/signup = anon, vaadin
/forgot-password = anon, vaadin
/reset-password = anon, vaadin
/registration-complete = anon, vaadin
/create-account = anon, vaadin
/payment = anon, vaadin
/environment = authc, vaadin[admin]
/billing = authc, vaadin[admin]
/settings = authc, vaadin[admin]
If we follow the link quickly after authorization, it will pass.
And if you wait for the application falls

Related

How to replace Servlet Filters already defined (replacing legacy doWithWebDescriptor with doWithSpring)

I'm trying to upgrade a Grails plugin from version 2.3.4 to 4.0.11. It uses a syntax that is no longer supported to replace filters with names sitemesh and urlMapping with its own filters.
The code below uses a DSL for xml. It replaces xml nodes in the final generated web.xml.
def doWithWebDescriptor = { xml ->
def pageFilter = xml.filter.find { it.'filter-name'.text() == 'sitemesh' }
def urlMappingFilter = xml.filter.find { it.'filter-name'.text() == 'urlMapping' }
def grailsVersion = GrailsUtil.grailsVersion
// Grails 1.3.x & Grails 2.0.x
def pageFilterClass = "org.zkoss.zk.grails.web.ZKGrailsPageFilter"
def urlMappingFilterClass = "org.zkoss.zk.grails.web.ZULUrlMappingsFilter"
if(grailsVersion.startsWith("2")) {
pageFilter.'filter-class'.replaceNode {
'filter-class'(pageFilterClass)
}
urlMappingFilter.'filter-class'.replaceNode {
'filter-class'(urlMappingFilterClass)
}
//
// Require a legacy config for servlet version
//
if(application.metadata.getServletVersion() >= '3.0') {
pageFilter.'filter-class' + {
'async-supported'('true')
}
urlMappingFilter.'filter-class' + {
'async-supported'('true')
}
}
} else {
pageFilter.'filter-class'.replaceBody(pageFilterClass)
urlMappingFilter.'filter-class'.replaceBody(urlMappingFilterClass)
}
}
What I tried so far
The code below uses Grails plugin configuration to register filters with spring's FilterRegistrationBean. I'm following Grails official documentation.
Closure doWithSpring() { { ->
boolean supportsAsync = this.grailsApplication.metadata.getServletVersion() >= "3.0"
pageFilter(FilterRegistrationBean) {
name = "sitemesh"
filter = bean(org.zkoss.zk.grails.web.ZKGrailsPageFilter)
urlPatterns = ["/*"]
order = Ordered.HIGHEST_PRECEDENCE
asyncSupported = supportsAsync
}
urlMappingFilter(FilterRegistrationBean) {
name = "urlMapping"
filter = bean(org.zkoss.zk.grails.web.ZULUrlMappingsFilter)
urlPatterns = ["/*"]
order = Ordered.HIGHEST_PRECEDENCE
asyncSupported = supportsAsync
}
}}
How can I replicate the legacy code with RegistrationBeans?
Also, I don't know if any of these filters got deprecated by Grails. I would like to know if there are any other replacements, if possible.
Here's the project in case anyone wants more context.
Debugging the older version of the plugin I came up with the following:
pageFilter(FilterRegistrationBean) {
name = "sitemesh"
filter = bean(ZKGrailsPageFilter)
urlPatterns = ["/*"]
order = OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER + 50
asyncSupported = supportsAsync
dispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR)
}
urlMappingFilter(FilterRegistrationBean) {
name = "urlMapping"
filter = bean(ZULUrlMappingsFilter)
urlPatterns = ["/*"]
order = OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER + 60
asyncSupported = supportsAsync
dispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD)
}
Added the dispatcherTypes and changed the order assuming these would be the last filters where the 'pageFilter' should be placed before the 'urlMappingFilter' in the filter chain.

Default Identity clashes with JWT

I have an ASP.NET Core 3.1 website that uses Identity for authentication on the actual customer-facing website. It also has an API backend that I want to secure with JWT for external user access.
However, using both authentication systems together is causing a problem. Setting the default authentication schemes to IdentityConstants.ApplicationScheme (or empty) causes JWT to fail authentication by routing API calls through the Identity scheme. Likewise, setting the schemes to JwtBearerDefaults.AuthenticationScheme causes the main site to fail by routing calls through the JWT scheme.
How can I separate the two so that anything routing through "/api" uses the JWT scheme and all other calls are handled by the default Identity scheme?
Here's part of the setup so far:
startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddDefaultIdentity<IdentityUser>(options => {
options.SignIn.RequireConfirmedAccount = true;
options.SignIn.RequireConfirmedEmail = false;
options.Password.RequireDigit = true;
options.Password.RequiredLength = 8;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Lockout.MaxFailedAccessAttempts = 5;
options.User.RequireUniqueEmail = true;
}).AddEntityFrameworkStores<ApplicationDbContext>();
...
services.AddAuthentication(x =>
{
// ** Playing with these settings **
//x.DefaultScheme = IdentityConstants.ApplicationScheme;
////x.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
////x.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
//x.DefaultForbidScheme = JwtBearerDefaults.AuthenticationScheme;
//x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
//x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = true;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = false,
IssuerSigningKey = new SymmetricSecurityKey(_SecretKey),
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
x.IncludeErrorDetails = true;
});
Any ideas would be most welcome. I'd prefer not to have to resort to plaintext Licence keys for the API functions.

WCF returning NULL values

I am calling a third party WCF service in MVC application.
When I am trying to read the response from service, I am getting all values as NULL, while if I check in fiddler it is showing response there.
Do I need any special configuration which I am missing in code? Please bear with me, as I am a new learner of WCF
Code is as below
SalesReviewMD efm = new SalesReviewMD(Server.MapPath("~/Cert/CertGlobal.pfx"), "*****");
#string stSales = new #string();
stSales.Value = "slo:cv";
IdentificationType salesJune = new IdentificationType();
salesJune.IdentificationID = stSales;
SaleType salesJuneType = new SaleType();
EntityType entity = new EntityType();
entity.id = "7yt678-0330-12312d-238-d4ww444f";
DateRangeType dt = new DateRangeType();
DateRangeType[] dtte = { dt };
SalesListType request = new SalesListType();
request.DocumentSubmitter = entity;
request.SendingSalesProfileCode = "urn:oasis:names:tc:legalxml-salesList:schema:xsd:WebServicesMessaging-2.0";
SalesListResponseMessageType response = efm.GetSalesList(request);
SalesListResponseMessageType from Wsdl
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.7.2612.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:oasis:names:tc:legalxml-salesList:schema:xsd:WebServicesMessaging-2.0")]
public partial class SalesListResponseMessageType : QueryResponseMessageType {
-------------------
-------------------
}

Using Neo4jUserManager

I'm new at Neo4j and I'm going to use neo4j.AspNet.Identity for my authentication and authorization. I'm using neo4jUserManager and also neo4jUserStore.But when I run the application, in Neo4jUserManager create method I'll face with NullExceptionReference and I don't know why? Can Anybody help me?
Below is my code
public class Neo4jUserManager : UserManager<ApplicationUser>
{
public Neo4jUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public async Task SetLastLogin()
{
// Store.FindByIdAsync()
}
public static Neo4jUserManager Create(IdentityFactoryOptions<Neo4jUserManager> options, IOwinContext context)
{
var graphClientWrapper = context.Get<GraphClientWrapper>();
var manager = new Neo4jUserManager(new Neo4jUserStore<ApplicationUser>(graphClientWrapper.GraphClient));
// Configure validation logic for usernames
// manager.UserValidator = new UserValidator<Neo4jUser>(manager)
// {
// AllowOnlyAlphanumericUserNames = false,
// RequireUniqueEmail = true
// };
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = false;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
// manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<Neo4jUser>
// {
// MessageFormat = "Your security code is {0}"
// });
// manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<Neo4jUser>
// {
// Subject = "Security Code",
// BodyFormat = "Your security code is {0}"
// });
// manager.EmailService = new EmailService();
// manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
To setup the graphClientWrapper, you can do this:
var gc = new GraphClient(new Uri("http://localhost.:7474/db/data"));
gc.Connect();
var graphClientWrapper = new GraphClientWrapper(gc);
var manager = new Neo4jUserManager(new Neo4jUserStore<ApplicationUser>(graphClientWrapper.GraphClient));
Also, as a side I would read up on how to use Owin. It should have been obvious to you that you're trying to pull from an IOwinContext object, and that if you're getting null you should investigate how to set that up. I imagine less than 5 minutes on Google would have helped you. OR just looking at what calls that method would have shown you how the EntityFramework was being setup in the template you're modifying.

401 error calling REST service from mvc controller

I am trying to make a request to a REST method and recieve the data in XML but this all goes well but when i want to use credentials for a method, because for this method you need to give credentials.
https://handshake:16a144bc5f480692d5c8d926068d2db5#rest-api.pay.nl/v2/Transaction/getStatus/xml/?orderId=236750347X6d2ee7
But when i use this one in the browser it work but this is not working from my controller.
//
// GET: /Home/Succes
public ActionResult Succes(string orderId)
{
string token = PaymentCalls.Login();
ViewBag.Token = token;
string _URL = "https://handshake:" + token + "#rest-api.pay.nl/v2/Transaction/getStatus/xml/?orderId=" + orderId;
NetworkCredential cr = new NetworkCredential("handshake", token);
XDocument doc = XDocument.Load(_URL);
var output = from feed in doc.Descendants("data")
select new Status
{
amount = feed.Element("amount").Value,
consumerAccountNumber = feed.Element("consumerAccountNumber").Value,
consumerCity = feed.Element("consumerCity").Value,
consumerEmail = feed.Element("consumerEmail").Value,
consumerName = feed.Element("consumerName").Value,
consumerZipcode = feed.Element("consumerZipcode").Value,
countryCode = feed.Element("countrCode").Value,
entranceCode = feed.Element("entranceCode").Value,
ipAddress = feed.Element("ipAddress").Value,
orderId = feed.Element("orderId").Value,
statsAdded = feed.Element("statsAdded").Value,
paymentSessionId = feed.Element("paymentSessionId").Value,
result = feed.Element("result").Value,
statusAction = feed.Element("statusAction").Value
};
return View(output);
So when we call this controller we get an 401 error but using the same url in the browser works. So i dont know but how can i set to pass credentials or something?

Resources